为什么填充会影响元素的宽度?

时间:2014-09-30 22:46:14

标签: css

<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>

正如你所看到的,我的页面上有2个DIV,为了响应,我只为百分比分配2个DIV的宽度。现在我希望#rest90 DIV中的内容与其左边界的距离为20px。但当我将#rest90的填充左侧设置为20px时,DIV将被移位。小提琴:http://jsfiddle.net/xvnj9oem/

我一直认为填充在元素内部,因此不应影响元素与其他元素的相对位置。但显然我错了,至少在这种情况下。我错过了什么吗?我是否必须为#rest90内的每个元素设置margin-left以实现我的目标?

4 个答案:

答案 0 :(得分:1)

简单地添加到您的div(或您需要的标签)

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

看看这个:CSS BOX SIZING

&#13;
&#13;
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 }
&#13;
<div id="container">
    <div id="left10"></div>
    <div id="rest90"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你应该看CSS Box Model

因为它运作正常:

#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>

答案 2 :(得分:0)

这是你想要做的吗?

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

答案 3 :(得分:0)

这是因为您没有使用box-sizing

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