css - `clear` 如何防止边距崩溃?

标签 css margin

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.

这是什么意思?你能给我一些具体的例子吗?

最佳答案

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

现在让我们从 float 开始并清除。 float 可以溢出其父级:

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

如果我们添加一个清除 div,它永远不会。明确就像说没有其他东西可以在这条线之上流动:

<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>

但是,边距折叠会稍微破坏一些东西,因为以下元素可以“穿过”某些内容折叠,一直到上边距的最顶部。让我们快速浏览一下边距折叠的某些方面。

self 崩溃黑客

一般来说,边距折叠适用于直接接触任何下边距的任何上边距。

这也包括元素自己的顶部/底部边距。这称为自折叠,并且边距折叠会重复发生。这是将这两件事结合在一起的一个简单示例:

<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 完全自折叠,导致计算出的空间为 30px,然后第二个 div 也折叠到其中,使空间保持在 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>

不过,利润仍然存在。它实际上在 float 上方向上运行 90 像素

接下来,假设其后没有文本,并且父级有下边距。根据我们的边距折叠规则,它应该向上折叠。兄弟元素甚至可能“穿过”它,一直折叠到顶部。我们不希望这样,因为这会导致一些不需要的重叠。

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

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

这描述了一个已清除 float 的自折叠元素。

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 添加一些文本使其不再自行折叠,但其底部边距会与父级的底部边距一起安全折叠。

关于css - `clear` 如何防止边距崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42569597/

相关文章:

html - 奇怪!重要的 margin

html - margin-block-start 和 margin-top 有什么区别?

CSS 边距怪癖 - 请帮助我理解

html - TCPDF 删除 <ul> 缩进

css - 删除图像和 div 之间的空间

jquery - bxSlider 在 Chrome 中调整大小时未调整大小(响应问题)

html - 在 Bootstrap 布局中重新排序 block

jquery - 多个 .CSS Jquery 行

html - 为什么页边距在我的页面顶部?

php - 使用 jQuery 调用填充 DIV 时不应用 CSS 样式