首页 文章

为什么父元素不包含保证金?

提问于
浏览
49

当具有边距的元素包含在另一个元素中时,父元素不会始终包装该边距 .

很多事情会导致父母包裹孩子的边缘:

  • border:solid;

  • 位置:绝对;

  • display:inline-block;

  • 溢出:自动

(这只是来自小型测试,毫无疑问还有更多 . )

我认为这与折叠边距有关,但是:

  • W3C规范页面没有此类行为的描述 .

  • 这里没有重叠的边距 .

  • 所有浏览器的行为在此问题上似乎都是一致的 .

  • 行为受与边距无关的触发器影响

默认溢出的元素的逻辑是什么:auto应该包含与溢出设置为auto的材料不同的材料 .

为什么除了常规div的默认行为之外的所有内容都假定父级包含保证金 - 为什么常规默认值不包括保证金?

编辑:最后的答案是W3C确实指定了这种行为,但那

演示:

<!doctype html>
<html>
<head>
<title>Margins overextending themselves</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css">
    body{
        margin:0;
    }
    div.b{
        background-color:green;
    }
    div.ib{
        display:inline-block;
        background-color:red;
    }
    div.pa{
        background-color:yellow;
        position:absolute;
        bottom:0; right:0;
    }
    div.oa{
        background-color:magenta;
        overflow:auto;
    }
    div.brdr{
        background-color:pink;
        border:solid;
    }

    h1{margin:100px; width:250px; border:solid;}
</style>
</head>
<body>
<div class="b">
    <h1>Is the margin contained?</h1>
</div>
<div class="ib">
    <h1>Is the margin contained?</h1>
</div>
<div class="pa">
    <h1>Is the margin contained?</h1>
</div>
<div class="oa">
    <h1>Is the margin contained?</h1>
</div>
<div class="brdr">
    <h1>Is the margin contained?</h1>
</div>
</body>
</html>`

1 回答

  • 27

    这就是CSS的工作原理according to W3C

    在本规范中,表达式折叠边距意味着两个或多个框(可能彼此相邻或嵌套)的相邻边距(没有非空内容,填充或边框区域或间隙将它们分开)组合形成单一保证金 .

    更具体到你的顶级div的情况:

    如果框的顶部和底部边距相邻,则边距可能会通过它折叠 . 在这种情况下,元素的位置取决于其与边缘正在折叠的其他元素的关系 . 如果元素的边距与其父元素的上边距折叠,则框的上边框边缘定义为与父元素相同 . 否则,元素的父元素不参与边距折叠,或仅涉及父元素的下边距 . 元素顶部边框边缘的位置与元素具有非零底边框时的位置相同 .

    我能做的最好的事情就是指向"Collapsing Margins" on sitepoint(汤米奥尔森和保罗奥布莱恩) . 他们做了一个详细的解释,其中的示例显示了您在问题示例代码中演示的行为 .

相关问题