如何`clear`防止保证金崩溃?

how `clear` prevent margin collapsing?

margin collapse 在以下情况下被禁用:

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.

这是什么意思?能举个具体的例子吗?

这确保清除可以防止任何后续元素与浮动重叠。

让我们从浮动开始,暂时清除。浮点数可以溢出它们的父元素:

<div style='border:1px solid green;'>
    <div style='float:left;background:red;height:100px;width:40px;'></div>
    That red box overflows!
</div>

如果我们添加空地 div,它永远不会。 clear 就像说没有别的东西可以流过这条线:

<div style='border:1px solid green;'>
    <div style='float:left;background:red;height:100px;width:40px;'></div>
    <div style='clear:both;'></div>
    <!-- Anything down here will not overlap the floats -->
</div>

但是,边距折叠会破坏一些东西,因为后面的元素会折叠'through' 某些东西,一直到顶部边距的最顶部。让我们快速浏览一下保证金崩溃的某些方面。

自我崩溃黑客

一般来说,边距折叠适用于 any 上边距,它直接接触 any 下边距。

这也包括一个元素自己的 top/bottom 边距。这称为自塌陷,并且边缘塌陷反复发生。这是将这两者结合在一起的简单示例:

<div style='margin-top:30px; margin-bottom:30px;'></div>
<div style='margin-top:30px; border:1px solid black;'>
    The gap above me is only 30px, not 90!
</div>

第一个 div 完全自我折叠,导致计算出的 space 为 30px,然后第二个 div 也折叠成那个,使 space 保持在仅 30px.

好的,我们现在对什么是自我崩溃有了一个大概的了解。现在让我们开始尝试通过 自崩溃清算来滥用它 div:

<div style='border:1px solid green;'>
    <div style='float:left;background:red;height:100px;width:40px;'></div>
    <div style='clear:left;margin-top:90px;margin-bottom:90px;'></div>
    I'm after the clear and look, no 90px gap!
</div>

虽然利润率仍然存在。它实际上在浮动 .

上方向上运行 90px

接下来,想象一下它后面没有文字,父级有一个底部边距。根据我们的保证金崩溃规则,它应该向上崩溃。兄弟元素甚至可能会折叠 'through' 它,一直到顶部。我们不希望这样,因为它会导致一些不必要的重叠。

规范的这一部分阻止了这种行为。让我们分解一下规范的语言以使其更清晰:

If the top and bottom margins of an element with clearance are adjoining

这是在描述一个已清除浮动的自折叠元素。

its margins collapse with the adjoining margins of following siblings

其他页边距塌陷进去没问题,但是..

That resulting margin does not collapse with the bottom margin of the parent block.

..最底部的边距不能向上折叠,因为那样会导致我们尴尬的重叠情况。

以下是应用规则的示例:

<div style='border:1px solid green;'>
    <!-- A parent block with a bottom margin, and no border -->
    <div style='margin-bottom:50px;'>
        <div style='float:left;background:red;height:100px;width:40px;'></div>
        <!-- A self collapsing cleared div -->
        <div style='clear:left;margin-top:50px;margin-bottom:50px;'></div>
        <!-- The parents bottom margin is adjacent to our collapsed margin, 
        but it gets blocked from collapsing upwards. We see a gap here -->
    </div>
</div>

在该空地上添加一些文本 div 使其不再自行折叠,但其底部边距随后会安全地与父级的底部边距一起折叠。