shenkwen
shenkwen

Reputation: 3880

why is padding affects a element's width?

<style type="text/css">
div{height:400px}
#container{width:100%}
#left10{width:10%;float:left;background:red}
#rest90{width:90%;float:left;background:yellow}
</style>
<div id="container">
    <div id="left10"></div>
    <div id="rest90"></div>
</div>

As you can see, I have 2 DIVs on my page, for responsive's sake, I only assign widths to the 2 DIVs in percentage. Now I want the contents in the #rest90 DIV has a 20px distance to its left border. But when I set #rest90's padding-left to 20px, the DIV will be displaced. Fiddle:http://jsfiddle.net/xvnj9oem/

I have always thought padding is inside an element, thus should not affect the element's relative position with other elements. But apparently I was wrong, at least in this case. Is there anything I missed? And do I have to set margin-left for every elements inside #rest90 to achieve my goal?

Upvotes: 0

Views: 1976

Answers (4)

You should look the CSS Box Model.

For it works properly:

#container{
    width: 100%;
}

#left10{
    width: 10%;
    float: left;
    background: red;
}

/** For width */
#rest90 {
    width: 90%;
    float: left;
}

/** For padding, margin and border */
/** The width of this container must be auto (default value) */
#rest90 > div {
    padding-left: 1px;
    background: yellow;
}


<div id="container">
    <div id="left10"></div>
    <div id="rest90"><div></div></div>
</div>

Upvotes: 0

dippas
dippas

Reputation: 60553

Simple as adding to your div (or the tag you need)

 -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
  -moz-box-sizing: border-box;    /* Firefox, other Gecko */
  box-sizing: border-box;         /* Opera/IE 8+ */

Take a look at this: CSS BOX SIZING

div{
 height:400px; 
 -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
 -moz-box-sizing: border-box;    /* Firefox, other Gecko */
 box-sizing: border-box;         /* Opera/IE 8+ */
}
#container{width:100%}
#left10{width:10%;float:left;background:red}
#rest90{width:90%;float:left;background:yellow; /*just to test padding*/ padding:20px }
<div id="container">
    <div id="left10"></div>
    <div id="rest90"></div>
</div>

Upvotes: 1

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

it is because you are not using box-sizing

div{height:400px;box-sizing:border-box}
#container{width:100%}
#left10{width:10%;float:left;background:red}
#rest90{width:90%;float:left;background:yellow}
<div id="container">
    <div id="left10"></div>
    <div id="rest90"></div>
</div>

Upvotes: 0

robert
robert

Reputation: 13

Is this what you're looking to do?

div {
    height:400px
}
#container {
    width:100%
}
#left10 {
    width:10%;
    float:left;
    background:red;
    left:0px;
    position:absolute;
}
#rest90 {
    padding-left:1px;
    width:90%;
    float:left;
    background:yellow;
    left:10%;
    position:absolute;
}

JSFiddle

Upvotes: 0

Related Questions