【发布时间】:2014-09-29 20:57:57
【问题描述】:
我正在尝试为容器 div 内的多个 div 元素设置边距。这是 HTML:
<div id="container">
<div id="square"></div>
<div id="square1"></div>
<div id="square2"></div>
</div>
这里是 CSS:
#container {
background: #ccc;
width: 200px;
height: 500px;
position: absolute;
overflow: initial;
}
#square {
margin-top: 10px;
height: 50px;
background: green;
}
#square2 {
margin-top: 275px;
height: 55px;
background: black;
}
现在,假设我要编辑正方形 1 的边距。这是更新后的 CSS:
#container {
background: #ccc;
width: 200px;
height: 500px;
position: absolute;
overflow: initial;
}
#square {
margin-top: 10px;
height: 50px;
background: green;
}
#square2 {
margin-top: 275px;
height: 55px;
background: black;
}
#square1 {
margin-top: 55px;
height: 50px;
background: red;
}
方块1的边距是正确的。但是,它弄乱了 square2 的边距,因为现在顶部边距是从 square1 而不是容器 div 测量的。如何将所有兄弟 div 的边距设置为从容器测量它们的位置,而不管其他兄弟 div 添加/删除了什么?任何帮助将不胜感激。
【问题讨论】:
-
类 square 是否打算在这里的某个地方使用?
-
不,我会删除它。
-
我猜你可以使用
position:absolute和top属性将div 定位到容器中。