BFC是什么
具有隔离作用的独立容器
创建条件
- 根元素
- 元素浮动
- 元素position为absolute,fixed
- 元素overflow值不为visible
- 元素display的值为inline-block,table-cell,table-caption
BFC的渲染规则
BFC在计算自身高度时会包含内部的浮动元素
<style>
.parent {
border: 1px solid green;
width: 600px;
}
.child {
height: 100px;
width: 400px;
background: yellow;
}
.float {
float: left;
height: 100px;
width: 400px;
background: orange;
}
</style>
<div class="parent">
<div class="child"></div>
<div class="float"></div>
</div>
上图可以看到,parent在计算自身高度时,会忽略掉浮动元素的高度,造成parent元素的高度塌陷。
当我们给.parent元素加上overflow:auto
时,满足上面条件4,因此parent元素会形成一个BFC,在计算自身高度时会包含内部的浮动元素
.parent{
border: 1px solid green;
width: 600px;
overflow:auto;
}
BFC不会与其他的兄弟元素发生关系,因此可以防止元素间的margin重叠
我们知道,内容在垂直方向上两个相邻div的margin会发生重叠,会以两个元素margin中最大的那个作为两个元素间的实际margin,这个时候就造成了margin垂直方向上的重叠。举例如下
<style>
.child1{
height: 100px;
width: 300px;
background: yellow;
margin: 20px;
}
.child2{
height: 100px;
width: 300px;
background: orange;
margin: 20px;
}
</style>
<div>
<div class="child1"></div>
<div class="child2"></div>
</div>
结果出来的布局效果却是
child1和child2都同时设置margin:20px
,由于相邻元素的margin垂直方向上会重叠,因此两个元素只有20px的margin。 为了防止margin的重叠,我们可以在child2元素外面包裹一层div,设置其overflow:auto
,使之成为一个BFC,这样BFC便不会与外界相邻元素发生关系,有效解决了该问题。
<style>
.child1{
height: 100px;
width: 300px;
background: yellow;
margin: 20px;
}
.child2{
height: 100px;
width: 300px;
background: orange;
margin: 20px;
}
.bfc{
overflow: auto;
}
</style>
<div>
<div class="child1"></div>
<div class="bfc">
<div class="child2"></div>
</div>
</div>
设置以上样式之后,.bfc形成了一个BFC,不会与外界相邻元素发生关系。
BFC不会与浮动元素重叠,因此可以简单的实现双栏布局
如果结合BFC的思想,一个BFC不会与兄弟元素发生关系。那么,如果当这个兄弟元素为浮动元素时,则为BFC元素区域不会与浮动元素发生重叠
<style>
.body-wrap{
height: 100px;
}
.left{
float:left;
width: 200px;
height: 100%;
background: blue;
opacity: 0.5;
}
.right{
height: 100%;
overflow:auto;
background: yellow;
}
</style>
<div class="body-wrap">
<div class="left"></div>
<div class="right"></div>
</div>