我正在阅读 W3C 规范,但我真的不明白 that one :
If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.
任何人都可以为我解释或 JSFiddle 吗?
最佳答案
是的。看看下面的片段 [JSfiddle] 在 Firefox 或 IE 中。¹
.case { width:200px; background-color:yellow; }
.container { background-color:lightblue; margin-bottom:70px; padding-top:0.01px; }
.preface { float:left; height: 58px; width: 100px; border: 1px solid red; }
.one .intro { clear: left; margin-top:60px; }
.two .intro { clear: left; margin-top:59px; }
<div class="case one">
<div class="container">
<div class="preface">
lorem ipsum
</div>
<div class="intro"></div>
</div>
after
</div>
<hr>
<div class="case two">
<div class="container">
<div class="preface">
lorem ipsum
</div>
<div class="intro"></div>
</div>
after
</div>
(除了类名“one”或“two”及其应用的 CSS 之外,其他情况完全相同。padding-top:0.01px;
用于停止 margin-top 值介绍 block 不会塌陷到容器的边缘顶部)
当一个元素应用了一个 clear
值时,它的盒子实际上向下移动,它被称为具有 clearance。我们可以看到这种情况发生在情况二中。在第一种情况下,盒子仍然有 clear:left
但它的上边距足够大,元素盒子不需要移动,所以它没有间隙。
现在看看结果。
在第一种情况下,容器上的 70px 底部边距与 .intro div 的顶部边距折叠,在 .container div 的顶部和文本“after”之间留下一个 70px 的距离。在第二种情况下,由于 .intro div 有间隙,根据引用的规范,容器的底部边距不得与 .intro div 的顶部边距重叠。因此应用上边距,产生浅蓝色背景区域,然后单独应用容器的底部边距,产生黄色背景区域。
¹不幸的是,Chrome 犯了这个可怕的错误。
关于css - margin 崩溃和清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25350805/