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

当具有边距的元素包含在另一个元素中时,父级不会一致地包装该边距。

许多事情会导致父母包装孩子的边际:

  • 边界:固体;
  • 位置:绝对的;
  • 显示:内联块;
  • 溢出:汽车
  • (这只是从小测试,毫无疑问还有更多。)

    我认为这与收缩利润率有关,但是:

  • W3C规范页面没有这种行为的描述。
  • 这里没有重叠边距。
  • 所有浏览器的行为在这个问题上似乎是一致的。
  • 行为受到与边距无关的触发器的影响
  • 默认为溢出的元素的逻辑是什么:auto应该包含与溢出设置为auto的元素不同的材料。

    为什么除了常规div的默认行为之外,其他所有的东西都假定margin是由父级包含的 - 为什么常规默认值不包含margin?

    编辑:最终的答案是,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>`
    

    根据W3C,这就是CSS的工作原理:

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

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

    如果一个箱子的顶部和底部边距相邻,则边缘可能通过它折叠。 在这种情况下,元素的位置取决于其与边缘正被折叠的其他元素的关系。

  • 如果元素的边距与父元素的顶部边距一起折叠,则该边框的顶部边缘被定义为与父元素相同。
  • 否则,元素的父代不参与边缘折叠,或者只涉及父代的底部边距。 元素上边框的位置与元素底边非零时的位置相同。
  • 我能做的最好的事情是指出你在站点上的“崩溃边缘” (Tommy Olsson和Paul O'Brien)。 他们做了非常详细的解释,并用实例向您展示了您在问题示例代码中演示的行为。

    链接地址: http://www.djcxy.com/p/87771.html

    上一篇: Why would margin not be contained by parent element?

    下一篇: Child elements with margins within DIVs