【问题标题】:Why margin of child div doesn't collapse with parent margin div为什么子 div 的边距不会与父边距 div 一起折叠
【发布时间】:2023-04-07 08:47:02
【问题描述】:

我正在尝试了解边距何时崩溃。

我关注了这篇文章:What’s the Deal with Margin Collapse?,但仍然不明白为什么以下边距不折叠。

我违反了哪条规则?

.container1 {
    background-color: red;
    border-style: solid;
    border-color: black;
    margin-top: 10em;
}
.container2 {
    background-color: green;
    border-style: solid;
    border-color: purple;
    margin-top: 10em;
}
<div class="container1">
    <div class="container2">
        aaaaa
    </div>
</div>

【问题讨论】:

  • 因为有边框The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.w3.org/TR/CSS2/box.html#collapsing-margins

标签: html css


【解决方案1】:

根据来自 W3.ORG 的Cascading Style Sheets (CSS) - The Official Difinition,他们说:

两个边距相邻当且仅当:

....

  • 没有线框、没有间隙、没有填充和没有边框分隔它们

...

在您的情况下,尝试像这样删除border-style: solid;

    .container1 {
        background-color: red;
        border-color: black;
        margin-top: 100px;
    }

    .container2 {
        background-color: green;
        border-color: purple;
        margin-top: 100px;
    }

折叠边距将会发生。

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 2015-12-26
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多