本文已参与「新人创作礼」活动,一起开启掘金创作之路
什么是BFC
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视化CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
怎么创建BFC
下列方式会创建块格式化上下文:
上面太多了不太好记,主要可以记住以下四种:
- body 根元素
- 浮动元素:float 除 none 以外的值
- 绝对定位元素:position (absolute、fixed)
- display 为 inline-block、table-cells、flex
- overflow 除了 visible 以外的值 (hidden、auto、scroll)
BFC 特性
- 使 BFC 内部浮动元素不会到处乱跑;
- 和浮动元素产生边界。
BFC常见作用
1、阻止外边距折叠
margin塌陷问题:在标准文档流中,块级标签之间竖直方向的margin会以大的为准,这就是margin的塌陷现象。可以用overflow:hidden产生bfc来解决。
<style>
div{
width: 100px;
height: 100px;
background: lightblue;
margin: 100px;
}
</style>
<body>
<div></div>
<div></div>
从效果上看,因为两个div元素都处于同一个BFC容器下(这里指body元素),所以第一个div的下边距和第二个div的上边距发生了重叠,所以两个盒子之间距离只有100px,而不是200px。
但这不是 CSS 的 bug,我们可以理解为一种规范,如果想要避免外边距的重叠,可以将其放在不同的 BFC 容器中。
<style>
.content1,.content2{
overflow: hidden;
}
.div1,.div2 {
width: 100px;
height: 100px;
background: lightblue;
margin: 100px;
}
</style>
<body>
<div class="content1">
<div class="div1"></div>
</div>
<div class="content2">
<div class="div2"></div>
</div>
</body>
2、包含浮动元素
高度塌陷问题,在通常情况下父元素的高度会被子元素撑开,而在这里因为其子元素为浮动元素所以父元素发生了高度坍塌,上下边界重合,这时就可以用BFC来清除浮动了。
<div style="border: 1px solid #000;">
<div style="width: 100px;height: 100px;background: grey;float: left;"></div>
</div>
由于容器内元素浮动,脱离了文档流,所以容器只剩下2px的边距高度。如果触发容器的BFC,那么容器将会包裹浮动元素。
<div style="border: 1px solid #000;overflow: hidden">
<div style="width: 100px;height: 100px;background: grey;float: left;"></div>
</div>
3、阻止元素被浮动元素覆盖
兄弟div浮动问题:由于左侧块级元素发生了浮动,所以和右侧未发生浮动的块级元素不在同一层内,所以会发生div遮挡问题。可以给右侧元素添加 overflow: hidden,触发BFC来解决遮挡问题。
<div style="height: 100px;width: 100px;float: left;background: lightblue">我是一个左浮动的元素</div>
<div style="width: 200px; height: 200px;background: grey">我是一个没有设置浮动,
也没有触发 BFC 元素, width: 200px; height:200px; background: grey;</div>
这时候其实第二个元素有部分被浮动元素所覆盖,但是文本信息不会被浮动元素所覆盖,如果想避免元素被覆盖,可触发第二个元素的BFC特性,在第二个元素中加入overflow:hidden,就会变成:
<div style="height: 100px;width: 100px;float: left;background: lightblue">我是一个左浮动的元素</div>
<div style="width: 200px; height: 200px;background: grey;overflow:hidden">我是一个没有设置浮动,
也没有触发 BFC 元素, width: 200px; height:200px; background: grey;</div>