首页 > 节点的margin-top影响其相对定位的兄弟节点

节点的margin-top影响其相对定位的兄弟节点

<head>
    <meta charset="utf-8">    
    <title></title>
    <style type="text/css">
        #div1{position: fixed;height: 100%;width: 100%;background: rgba(250,250,250,0.8);}
        #div2{height: 20px;width: 80px;margin: 80px auto;background-color: red;}
    </style>
</head>
<body>
   <div id="div1"></div>
   <div id="div2"></div>
</body>

先说结论,这个问题的实质其实不是margin影响相对定位的兄弟元素节点,而是影响了父元素,也叫外边距共享问题。

题主不妨打开浏览器的f12查看一下

所以其实看似引起了div1的margin-top,实际上是作用在body上,接下来给出解释:

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分隔

换言之,在这里我们的设置达到了父元素与子元素共享margin的要求,所以出现了题主所看到的状况;
既然知道了原因,解决办法也就找到了--破坏共享margin的要求即可:给body添加padding-top或者border-top即可
如下:

【热门文章】
【热门文章】