子元素 margin-top 会影响父元素(overflow)

介绍

在外部div,内部第一个div有margin-top样式时,内部div的margin-top样式会影响外部div的居顶,为了不影响外部div,需要在外部div加上该样式

提出问题

css:

<style type="text/css">
        *{
            margin: 0px; padding: 0px; 
        }
        .show{
            margin: 0px auto;
            width: 200px;
            height: 100px;
            background-color: #999999;
        }
        .show h2{
            margin-top: 50px;/*important*/
            cursor: pointer;
        }
    </style>

html:

<div class="show">
    <h2>crystal</h2>
</div>

当在 <h2>crystal</h2> 没有设置 margin-top 时,浏览器显示如下图:

设置了margin-top后出现了如下所示的现象:

分析

没有给外层的 div 设置 margin-top ,但是还是距离浏览器最顶部产生了 50px 的间距,查看这 50px 间距属于哪个元素,会发现外层 div 的 margin 依然是 0 auto ; 所以这个margin 还是属于 h2

原因

css2.1盒模型中规定的内容:

In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.

翻译:

所有毗邻的两个或更多盒元素的 margin 将会合并为一个 margin 共享之。

毗邻的定义为:同级 或者 嵌套的盒元素,并且它们之间没有非空内容、Padding或Border分隔。

总结原因:

因为嵌套也属于毗邻,所以 h2 和 外层 div 的 margin 合并成一个,导致 div 产生 10px 的间距。

解决

  1. 父元素或子元素使用浮动或者绝对定位 absolute。浮动或绝对定位不参与margin的折叠

  2. 父元素设置 overflow:hidden;

  3. 父元素 或 子元素设置 padding

  4. 父级设置 border

感谢:
https://blog.csdn.net/sinat_27088253/article/details/52954688


原文出处:/show_1IX3879Zs8e3.html