那是我的代码笔:http://codepen.io/helloworld/pen/JoKmQr
在 IE 11 上运行。
为什么当我将 5% 的填充设置为 itemContainer 时,右侧的红色div 溢出到屏幕中?
<div style="background:lightblue;">Absolute position inside container</div>
<div id="itemContainer">
<div class="item i1">1</div>
<div class="item i2">2</div>
<div class="item i3">3</div>
</div>
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body, html {
padding: 0;
margin:0;
height:100%;
}
.item{
position:absolute;
}
#itemContainer{
background:orange;
height:100%;
position:relative;
padding:5%;
}
.item.i1 {
width: 50%;
height:50%;
background:lightgreen;
}
.item.i2 {
width: 50%;
height:50%;
top:50%;
background:lightgray;;
}
.item.i3 {
width: 50%;
height:100%;
left: 50%;
background:red;
}
更新
我的目标是在屏幕上放置 3 个具有"2 列"布局的项目,第 2 个"列"的项目应通过赋予它 100% 的高度来模拟"行跨度",而项目 1 和 2 具有 50% 的高度。
发生这种情况是因为填充被计为高度的一部分 - 如果您要在#itemContainer
上放置一个"内部"div 并在外部div 上设置填充,您将能够修复它。在这里看到我的叉子:http://codepen.io/anon/pen/XJMMoZ
填充没有任何问题(当使用框大小时:边框框;)。
#itemContainer 具有位置:相对。
子div (.item) 具有位置:绝对。
要绝对定位子项(.item),浏览器需要知道相对于位置(上,左,右和下)。
在您的示例中,只需将这些"定位"属性添加到绝对定位的div 中:
.item{
position:absolute;
}
.item.i1 {
width: 50%;
height:50%;
background:lightgreen;
top:0;
left:0;
}
.item.i2 {
width: 50%;
height:50%;
top:50%;
background:lightgray;
bottom:0;
left:0;
}
.item.i3 {
width: 50%;
height:100%;
left: 50%;
background:red;
top:0;
right:0;
}
http://codepen.io/anon/pen/GgWVjY
被计为内容元素的宽度/高度的加法,而不会注意到其填充。
如果你有 5% 的填充,你需要将内容设置为 90% 的宽度和高度,因为你已经有 10% 的填充(5% 顶部和 5% 的底部分别是 5% 的左侧和 5% 的右侧。
对于 50% 的内容块,您需要将其更改为 45%。100% 得到 90%。
这样它应该适合。
我建议重写你的代码,这样它就不会使用绝对定位的元素,特别是对于列这样的东西,否则你会继续遇到这样的问题。由于填充而必须将宽度从 100% 减少不应该是必需的,尤其是当 border-box 会阻止这种需求时,但即便如此,我仍然建议这样:
.HTML:
<div class="container">
<div class="leftCol">
<div class="box1"></div>
<div class="box2"></div>
</div><!--
--><div class="rightCol">
</div>
</div>
.CSS:
.container {
display: block;
width: 50%;
height: 500px;
padding: 25px;
background: #DDD;}
.leftCol,
.rightCol {
display: inline-block;
vertical-align: top;
height: 100%;
width: 50%;}
.leftCol {
background: #BBB;}
.rightCol {
background: #CCC;}
.box1 {
display: block;
width: 100%;
height: 50%;
background: gray;}
.box2 {
display: block;
width: 100%;
height: 50%;
background: #555;}