什么是BFC
块格式化上下文(Block Formatting Context,BFC)是 Web 页面的可视 CSS 渲染的一部分,是块级盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
渲染规则
- 内部盒子会在垂直方向上一个接一个摆放
- 对于同一个BFC的两个相邻盒子的margin会发生重叠(坍塌),与方向无关
- 每个元素的左外边距与包含块的左边界相接触(从左到右),即使浮动元素也是如此
- BFC的区域不会与float元素区域重叠
- 计算BFC高度时,会计算浮动子元素的高度
- BFC是页面上的一个隔离独立容器,容器中的子元素不会影响到外面的元素
触发条件
- 根元素
<html> - 浮动
- 绝对定位 position: absolute|fixed
- overflow值不为 visible|clip
- cloumn-count或者clumn-width不为auto
- display: inline-block|table-cell|table-caption|table|flow-root|flex|grid
- contain: layout|content|paint
应用场景
包含内部浮动
让浮动内容和周围内容等高
<!-- 包含内部浮动 -->
<div class="bfc">
<div class="float"></div>
</div>
.bfc{
/* overflow: hidden; */
background: red;
border: solid 1px red;
}
.float{
width: 200px;
height: 200px;
background-color: blue;
float: left;
}
当父元素不是BFC时,不会包含浮动元素的大小
当把overflow设置成hidden(父元素设置成BFC) ,父元素会包含float子元素的大小
清除外部浮动
参考渲染规则
每个元素的左外边距与包含块的左边界相接触(从左到右),即使浮动元素也是如此
浮动元素会覆盖在之后的元素上
把之后的元素设置成BFC,则不会受到浮动元素的影响
<!-- 清除外部浮动 -->
<div class="float"></div>
<div class="bfc"></div>
.bfc{
overflow: hidden;
height: 980px;
background: red;
}
.float {
float: left;
width: 200px;
height: 800px;
background-color: blue;
}
外边距重叠
<!-- 外边距塌陷 -->
<div class="bfc">
<div class="blue"></div>
<div class="pink"></div>
</div>
.blue{
width: 200px;
height: 200px;
background-color: blue;
margin: 200px;
}
.pink{
width: 200px;
height: 200px;
background-color: pink;
margin: 100px;
}
根据BFC的渲染规则,对于同一个BFC的两个相邻盒子的margin会发生重叠(坍塌),与方向无关.
两个盒子之间的上下距离是200px,也就是说有100px重叠了
解决方法,新建一个BFC区域,其内部的元素就不会影响外部元素了
.bfc{
overflow: hidden;
/* background: red; */
}
.blue{
width: 200px;
height: 200px;
background-color: blue;
margin: 200px;
}
.pink{
width: 200px;
height: 200px;
background-color: pink;
margin: 100px;
}
.wrap {
display: flex;
}
<!-- 外边距塌陷 -->
<div class="bfc">
<div class="blue"></div>
<div class="wrap">
<div class="pink"></div>
</div>
</div>