html - 看不懂这个边距崩溃的例子

标签 html css

当我们在外部 div 上有边框时,我可以理解下面的第一个示例。 边距崩溃,所以我们只有 20 像素的边距。

但是第二个例子看起来很奇怪当我们只是
去除外层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

最佳答案

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

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

关于html - 看不懂这个边距崩溃的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243812/

相关文章:

javascript - Bootstrap 下拉菜单 jQuery 与其他库冲突?

html - 设置AngularJS Material 中下拉列表的默认值

html - CSS 边框图像仅适用于顶部和底部

html - 想要避免使用 CSS box-shadow 隐藏之前的 li 元素

javascript - 带有 Leaflet 的 map 不起作用

html - 使用 flexbox 将多个文本居中

html - 为什么这个 CSS font-face 代码不加载字体?

javascript - 谷歌地图捏缩放事件

php - EXCEL:如何在excel中添加背景标题颜色;使用 PHP 导出?

html - 如何使用 iframe 和移动查询更改宽度和高度?