我被告知内部元素的百分比宽度是基于外部元素的总宽度计算的,并且该外部元素的边距和填充是基于外部元素的内容宽度计算的。当我尝试使用它不起作用。我根据外部元素的内容宽度获得所有内容(宽度,填充和边距)。这是我的CSS: <
style>
html {
background: url(images/grid.gif) 5px 5px;
}
body {
font: 100% Arial, Arial, Helvetica, sans-serif;
}
html, body{
margin:0 auto;
}
.outer{
margin:50px;
padding:50px;
width:300px;
height:300px;
background:red;
}
.inner{
width:50%;
height:50%;
background:navy;
}
</style>
这是我的HTML:
<html>
<body>
<div class="outer">
<div class="inner">
</div>
</div>
</body>
</html>
我的内部元素的50%宽度的宽度为150px而不是200px,因为填充应该总计,并且外部元素填充的50px以及300px宽度应该总计400px。保证金不应该是内容宽度的一部分?我认为? 边距和填充百分比是否与宽度百分比不同?
答案 0 :(得分:2)
计算容器盒尺寸有不同的模型。
这是一个非常好的阅读,以获取更多信息:http://css-tricks.com/box-sizing/
如果您希望inner
完全为outer
的50%,则应尝试使用border-box
框大小调整。
.outer, .inner
{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
然后申请
.inner
{
width:50%;
}
现在,这些元素的填充,边框和宽度将计算为cotainer宽度。
更新
这是两种盒子大小调整方法的小提琴: http://fiddle.jshell.net/Rx9CX/
在这个例子中,我的JS非常糟糕,你可以看到,你使用的测量方法也很重要。如果你看一下jQuerys width()方法(https://api.jquery.com/width/),可以看一下这种行为:
请注意,无论如何,.width()将始终返回内容宽度 CSS box-sizing属性的值。从jQuery 1.8开始,这可能会 需要检索CSS宽度加上box-sizing属性然后 减去每个元素上的任何潜在边界和填充 element有box-sizing:border-box。为避免这种惩罚,请使用.css( “width”)而不是.width()
在小提琴中你可以看到width()和innerWidth()之间的区别。
答案 1 :(得分:0)
如果.outer的宽度为:300px; ,然后.inner宽度:50%;表示150px
答案 2 :(得分:0)
这取决于你使用的读者。
试试这个: http://jsfiddle.net/33EZ3/
.outer{
margin:50px;
padding:50px;
width:300px;
height:300px;
background:red;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
.inner{
width:50%;
height:50%;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other G */
background-color: navy;
}