【问题标题】:Don't understand this example with margin collapse不理解这个边距崩溃的例子
【发布时间】:2013-08-15 07:19:15
【问题描述】:

当我们在外部 div 上有边框时,我可以理解下面的第一个示例。 边距折叠,所以我们只得到 20px 边距。

但是第二个例子看起来很奇怪,当我们刚刚
从外部 div 中删除边框

/*Fist example */
<!DOCTYPE HTML>
<html lang="en">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
    <title>"float: left" with no width set</title>
    <style type="text/css" media="screen">
        body
    {
            padding: 0;
        margin:1px;
    }
        </style>
    </head>
    <body>
        <div style="background-color: yellow; border: solid 1px #ccc;">
            <div style="margin: 20px; background-color: red;">
                <p style="margin: 20px; color:#fff; background-color: blue;">A paragraph 
                     with a  20px margin inside a div, also with a 20px margin</p>
            </div>
        </div>
    </body>
</html>

/* Secod example without a border on the outer div */
<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
    <title>"float: left" with no width set</title>
    <style type="text/css" media="screen">
     body
     {
         padding: 0;
         margin:1px;
    }
        </style>
    </head>
    <body>
        <div style="background-color:yellow;">
            <div style="margin: 20px; background-color: red;">
                <p style="margin: 20px; color:#fff; background-color: blue;">
                       A paragraph with a 20px margin inside a div, also with a 20px margin
                </p>
            </div>
        </div>
    </body>
</html>

//Tony

【问题讨论】:

  • 第二个示例中是否应该出现语法错误?浮动设置在标签之外

标签: html css


【解决方案1】:

两个边距相邻当且仅当...没有行框、没有间隙、没有填充和没有边框将它们分开

见:http://www.w3.org/TR/CSS2/box.html#collapsing-margins

【讨论】:

    【解决方案2】:

    因为如果边框(或填充)将块级父级与其第一个流入块级子级边距分开,则不会折叠。另请注意,在浮动元素、显示值为 inline-block 的元素或绝对定位元素上,边距不会折叠。正如 Toxz 所指出的,请查看spec 以获得深入的解释:

    流入块元素的上边距与其第一个元素一起折叠 如果元素有 no 顶部,则流入块级子级的上边距 边框,没有顶部填充,孩子没有间隙

    【讨论】:

    • 那么当我们在这种情况下讨论“崩溃”时,它只是指背景发生的事情吗?因为看起来边缘仍然“存在”,产生空间,即使它不是黄色:plnkr.co/edit/Q0EOj3aoWFLS1xFyMhsL?p=preview
    • 在这种情况下 - 是的。但是,如果您查看此fiddle 并删除&lt;p&gt; 上的float: left; 规则,您将看到它如何影响元素的定位。让我知道这是否有意义。
    • 感谢 Adrift 的示例!那么是否没有与这两个示例相关的一般定义(或概念)?也就是说,什么情况下“塌陷”只影响背景,什么情况下会影响实际空间?我注意到,例如,我可以用 display:inline-block 替换 float:left 并且边距空间仍然存在。有没有更深层次的概念在起作用?
    • 不幸的是,它取决于许多变量。一个 inline-block 的元素永远不会有边距折叠,就像浮动和绝对/固定定位的元素一样——即使是它们的流入块级后代也不例外。这对我来说有点难以解释,我建议阅读 Toxz 和我提供给规范的链接并尝试一下。
    猜你喜欢
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2017-07-23
    • 1970-01-01
    • 2012-07-12
    相关资源
    最近更新 更多