Collapsing margins——合并的外边距
2014年3月15日 05:10
昨天在写 CSS 时遇到一个小问题,困扰了我好长时间,最后 Google 之,发现早有前人踩过此坑。为免以后再掉进坑,记下来比较好。
昨天遇到的问题是这样的。我设置了一对父子元素如下:
<div class="parent">Parent
<div class="children">Children
</div>
</div>
<div class="divider"></div>
它们的样式如下:
.parent {
margin-bottom: 10px;
width: 80px;
height: 20px;
background-color: yellow;
}
.children {
margin-bottom: 20px;
width: 80px;
height: 20px;
background-color: red;
}
.divider {
height: 1px;
background-color: black;
}
产生的效果如图所示:
![][1]
为什么分割线跑到了 Children 里面?这两个父子元素都设置了 margin-bottom,加起来应该是 30px,为什么现在成了 20px?种种疑问在我脑中盘旋。刚开始以为是万恶的 position,但是我把所有能想到的属性排列组合都设置了一遍,发现还是不行。果断 Google,才知道这个问题由来已久……
collapsed margin
关于 collapsing-margin,有 [W3C 的官方介绍][2]:
Continue to readIn CSS, the adjoining m...