CSS-margin外边距折叠
外边距折叠指的是,块的上外边距(margin-top)和下外边距(margin-bottom)有时合并(折叠)为单个边距,其大小为单个边距的最大值(或如果它们相等,则仅为其中一个),这种行为称为边距折叠。—MDN
注意:外边距折叠仅仅指的是垂直外边距,并且只发生在处于文档流的块状元素中
解决方案:
1、设置padding或border处理外边距折叠问题
2、将元素BFC(块级格式化上下文)化,只有属于同一个BFC的元素才会发生垂直外边距折叠,例如设置overflow:hidden
1、兄弟元素外边距折叠
示例代码:
.div1{
margin-bottom: 10px;
width: 100px;
height: 100px;
background-color: pink;
}
.div2{
margin-top: 20px;
width: 100px;
height: 100px;
background-color: #aaaa;
}
<div class="div1">div1</div>
<div class="div2">div2</div>
示例效果:
2、父子元素外边距折叠
父子元素外边距折叠发生的前提条件是:二者垂直外边距之间没有padding、border,开发中常见body的儿子元素设置margin-top会导致body下移。文档流中父元素的第一个子元素的margin-top会向上寻找padding或者border,如果找不到会把自己的margin-top给父元素。
示例代码:
body{
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.box1{
border: 1px solid pink;
width: 200px;
height: 200px;
background-color: pink;
}
.box2{
width: 100px;
height: 100px;
background-color: yellow;
}
.box3{
margin-top: 10px;
width: 50px;
height: 50px;
background-color: red;
}
<div class="box1">
<div class="box2">
<div class="box3"></div>
</div>
</div>
效果示例:
3、空元素上下边距折叠
一个空元素会将自己的如果没有padding或者border分割,也会将自己的上下边距折叠
.item1{
background-color: #222;
margin: 20px 0;
}
<div class="item1"></div>
示例效果:
4、总结
外边距折叠发生条件以及解决:
- 外边距折叠发生在处于同一个BFC内的元素
- 只有垂直方向会发生
- 如果元素垂直方向中间有margin或者border,垂直外边距不会发生折叠
- 设置元素的BFC也可以避免垂直外边距折叠。
BFC相关
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
常用的设置BFC
设置浮动(folat不能为none)、
定位(absolute、fixed)、
overflow(不为visible)、
display(inline-block,
table-cell,
table-caption,
flex, inline-flex,
grid, inline-grid,
flow-root:一个新的 display 属性的值,它可以创建无副作用的BFC,等同于<html>根标签是一个BFC。)
等等。。。。。。