10
09/2014
Collapsing margins
标题
文字
标题
文字
html 代码
<ul id="collapsing-margins-div" style="margin: 0;padding: 0;list-style: none;background:red;">
<li style="float:left;width:50%;">
<div style="background:green" class="wrapper">
<h3>标题</h3><p>文字</p>
</div>
</li>
<li style="float:left;width:50%;">
<div style="background:blue" class="wrapper">
<h3>标题</h3><p>文字</p>
</div>
</li>
<div style="clear:both;"></div>
</ul>
<style>
#collapsing-margins-div li:hover {background-color: #333;}
</style>
问题
注意:那个莫名其妙的 红边,实际上是由 h3 的 margin-top 产生的!
#collapsing-margins-div h3 {margin-top: 0;}
难道这就是传说中的 collapsing-margins
h1 {
margin: 0 0 25px 0;
background: #cfc;
}
p {
margin: 20px 0 0 0;
background: #cf9;
}

简单的说:上下两个相邻元素之间的 margin 会合并为大的那个!除非发生以下情况之一
- float 浮动
- position:absolute
- inline-block
- 父元素 overflow:auto 或者 overflow:scroll 或者 overflow:visible
- clear:xxx
- root element
结论
这就是为什么 gs-accordin.less 中出现下面的
//fix inside first and last elements overflow parent!!
parent {
:first-child {margin-top:0 !important;margin-left:0 !important;}
:last-child {margin-bottom:0 !important;margin-right:0 !important;}
}
当然,上面那些 float,display:inline-block 等办法也可以。
参考: