《精通css 高级web标准解决方案》一书讲到盒模型的时候、这么说到:外边距甚至可以与本身发生叠加。假设有一个空元素,他有外边距,但是没有边框或内边距。在这种情况下,顶外边距与底外边距就碰到了一起,它们会发生叠加。
并且给出了图事例,如下图:
根据它所说我写下了如下代码,
<body>
<div style="margin-top:20px;margin-bottom:20px"></div>
</body>
按照它的意思是不是这个空的div就只占据20px呢?但是实际上在浏览器中看到如下图所示,
它还是占据了40px而不是20px哇?是我理解的不对么?
但是我又写下了如下代码,
<body>
<div style="margin-top:20px;margin-bottom:20px"></div>
<div>Test</div>
</body>
这时,包含Test的div的margin-top
就是20px而不是40px了,莫非是按照我第二种理解来么?只有当有多个元素的时候,才会发生如书上所说的叠加,而当页面上只有一个空元素的时候并不会发生margin-top
与margin-bottom
的叠加。
是这样理解的么?
margin重合是指两个相邻的元素了
<style>
div{
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<div></div>
<div></div>
像这种情况,第一个DIV的margin-bottom会和第二个DIV的margin-top合并,最终两个DIV间的margin为最大的那个margin,也即是10px
<div di="emptyDiv" style="margin-top:30px;margin-bottom:20px"></div>
<div id="divB" style="margin-top:20px;margin-bottom:20px;height:20px;background-color: #0E2D5F"></div>
运行后效果如下
你可以发现divB的内容上边界距离emptyDiv的上外边距之间的距离为30px,也就说emptyDiv通过maring-top和margin-bottom的合并将divB放在其下30px处~~
而divB的margin-top:20px;小于emptyDiv合并后的margin-bottom:30px(margin-top可以认为不存在了),所以位置不变
如果divB的margin-top:50px;那么divB将被放在emptyDiv下50px;