1

当我们在外部 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
4

2 回答 2

1

Because if a border (or padding) separates a block-level parent with it's first in-flow block-level child margins will not collapse. Also note that margins will not collapse on an element that is floated, elements that have a display value of inline-block or absolutely positioned elements. As Toxz pointed out, take a look at the spec for an in-depth explanation:

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

于 2013-08-14T23:19:15.273 回答
1

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

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

于 2013-08-14T23:15:23.450 回答