CSS 外边距合并(或折叠)
借用MDN的定义:块级元素的上外边距(margin-top)和下外边距(margin-bottom)有时会合并(或折叠)为一个外边距,这种行为称为外边距折叠(margin collapsing) 有时也翻译为外边距合并。注意: 浮动元素和绝对定位元素的外边距不会折叠(因为这里触发了块格式化上下文[Block Formating Context, BFC])
情景
相邻元素之间
借用MDN的定义:想邻的两个元素之间的外边距会折叠(除非后一个元素需要清除之前的浮动)。
<style>
div {
width: 50px;
height: 50px;
background-color: red;
}
.par2 {
margin-bottom: 20px;
}
.par3 {
float: left;
margin-top: 30px;
}
</style>
<body>
<div class="par2"></div>
<div class="par3"></div>
</body>
代码的结果图为:
去除.par3的 float: left的属性后,结果图为:
父元素与其第一个或最后一个子元素之间
借用MDN的定义:
如果父元素与其first-child之间不存在border
,padding
,content
,也没有创建BFC、或者子元素浮动
将两者的margin-top
分开;如果父元素与其last-child之间不存在border
、padding
、content
、height
、min-height
、max-height
将两者的margin-bottom分开,那么这两对外边距之间会产生折叠。此时子元素的外边距会‘溢出’到父元素外面去
咋们一个一个来试试
父元素与第一个子元素
基本代码
<html>
<head></head>
<style>
.par1 {
height: 10px;
background-color: #12bcfc;
}
.par2 {
width: 100px;
margin-top: 20px;
margin-bottom: 20px;
margin-left: auto;
margin-right: auto;
background-color: blue;
}
.par2 .child {
width: 40px;
height: 40px;
margin-top: 20px;
margin-bottom: 30px;
background-color: black;
}
</style>
<body>
<div class="par1"></div>
<div class="par2">
<div class="child"></div>
<div class="child2"></div>
</div>
</body>
</html>
- 什么都没有的情况下,外边距会折叠
-
它们之间有
content
时
-
它们之间有
padding
时
-
它们之间有
border
时
-
当父元素成为一个成为独立的BFC时,外边距折叠会消失。至于BFC形成的条件,参见文档
补充: contain 值为 layout、content或 strict 的元素
- 当父元素的first-child,设置如下属性值(形成BFC的属性值)时,外边距折叠会消失.
父元素与第一个子元素
-
情况1-5与
父元素与第一个子元素
的情况一样 -
情况6不太一样。子元素浮动后,父元素高度会减小(因为不能设置height,min-height,max-height),所以浮动后布局乱了,如果父元素清除了浮动,那就跟情况5一样了,父元素成了独立的BFC。
-
我最中测试发现,last-child只有设置了
display: inline-block;
或者table-caption
时,才能去除外边距折叠