深入理解 BFC
大约 2 分钟
深入理解 BFC
何为BFC
CSS 中“BFC”的概念,全称叫“Block Formatting Context”,中文叫“块级格式化上下文”,是Web页面中盒模型布局的CSS渲染模式,指一个独立的渲染区域或者说是一个隔离的独立容器。
形成BFC的条件
- 1、浮动元素,float 除 none 以外的值;
- 2、定位元素,position(absolute,fixed);
- 3、display 为以下其中之一的值 inline-block,table-cell,table-caption;
- 4、overflow 除了 visible 以外的值(hidden,auto,scroll);
BFC的特性
- 1、内部的Box会在垂直方向上一个接一个的放置。
- 2、垂直方向上的距离由margin决定
- 3、bfc的区域不会与float的元素区域重叠。
- 4、计算bfc的高度时,浮动元素也参与计算
- 5、bfc就是页面上的一个独立容器,容器里面的子元素不会影响外面元素。
BFC 被用烂了的 2 个场景分别是清除浮动影响(clear the floats)和避免外边距合并(prevent margins collapsing)。
清除浮动
不被浮动元素覆盖
实现效果:左边固定宽度,右边不设宽,因此右边的宽度自适应,随浏览器窗口大小的变化而变化
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.column:nth-of-type(1) {
float: right;
width: 200px;
height: 100px;
margin-right: 10px;
background-color: red;
}
.column:nth-of-type(2) {
height: 300px;
background-color: purple;
}
</style>
</head>
<body>
<div class="column"></div>
<div class="column"></div>
</body>
</html>
效果如下:

这里第一个元素给了浮动效果,不管是左浮动还是右浮动,上面代码都产生了重叠,这里给第二元素加上overflow: hidden;创建BFC
.column:nth-of-type(2) {
overflow: hidden;/*创建bfc */
height: 300px;
background-color: purple;
}
效果如下:

## 避免外边距合并(margin重叠) 在布局中常常还会遇到的一个场景就是外边距合并
<div class="outer">
<p>I am paragraph one and I have a margin top and bottom of 20px;</p>
<p>I am paragraph two and I have a margin top and bottom of 20px;</p>
</div>
<style>
.outer {
background-color: gray;
}
p {
margin: 20px 0 20px 0;
background-color: pink;
}
</style>
效果如下:

这里有两个地方产生了外边距合并:一个是 <p>
之间的外边距合并,一个是 <p>
与父元素 .outer 之间产生的外边距合并。前者是合理的,但父子元素之间的外边距合并结果就不是理想的。 父子元素之间的外边距合并意外导致了父元素高度塌陷。这个时候我们就可以通过给父元素创建 BFC 来解决这个问题。
.outer {
background-color: #ccc;
overflow: auto;
}
效果如下:

这一点还是反应了 BFC 是一个完全独立的环境,不会影响外部元素布局