什么是BFC
BFC全称是Block Formatting Context,即块格式化上下文。它是一块独立的渲染区域,在该区域中,它规定常规流块盒布局方式。
我们常说的文档流其实分为定位流、浮动流、普通流三种。而普通流其实就是指BFC中的FC。FC(Formatting Context),直译过来是格式化上下文,它是页面中的一块渲染区域,有一套渲染规则,决定了其子元素如何布局,以及和其他元素之间的关系和作用。
BFC是一块渲染区域,那这块渲染区域到底在哪
- 根元素
- 浮动元素和定位元素(相对定位除外)
- overflow的值不为visible
- display的值为inline-block、table-cell、table-caption
它解决的一些问题
1.不会与浮动元素进行重叠
<style>
.one{
float: left;
width: 200px;
height: 200px;
background: red;
}
.two{
height: 300px;
background-color: green;
}
</style>
<div class="one"></div>
<div class="two"></div>
以上代码的效果
当我们将绿色盒子变为BFC时,就不会重叠了
.two{
height: 300px;
background-color: green;
overflow: auto;
}
2.高度需要计算浮动元素
<style>
.container{
width: 500px;
border: 2px solid;
}
.item{
width: 200px;
height: 100px;
float: left;
background: red;
margin: 10px;
}
</style>
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
因为内部子元素浮动,所以高度塌陷了
.container{
width: 500px;
border: 2px solid;
/* float: left; */
/* position: absolute; */
/* 带来的影响时最小的 */
overflow: auto;
}
将其变为BFC后,浮动元素高度也重新计算
3.与子元素发生外边距重叠
<style>
.container{
width: 300px;
height: 300px;
background: red;
}
.item{
width: 100px;
height: 100px;
background: #008c8c;
margin-top: 20px;
}
</style>
<div class="container">
<div class="item"></div>
</div>
以上子元素与父元素一起下移了
.container{
width: 300px;
height: 300px;
background: red;
overflow: auto;
}
加了overflow:auto;变为BFC后
外边距没有重叠在一起了
总结
- 创建BFC的元素,它的自动高度需要计算浮动元素
- 创建BFC的元素,不会与浮动元素进行重叠
- 创建BFC的元素,不会与子元素发生外边距重叠