BFC及应用

什么是 BFC

BFC 全称 Block Formatting Context 即块级格式上下文,简单的说,BFC 是页面上的一个隔离的独立容器,不受外界干扰或干扰外界。
可以把 BFC 理解为一个封闭的大箱子,箱子内部的元素无论如何翻江倒海,都不会影响到外部。

触发 BFC

  • body 根元素
  • 浮动元素:floatnone 以外的值
  • 绝对定位元素:position (absolutefixed)
  • displayinline-blocktable-cellsflex
  • overflow 除了 visible 以外的值 (hiddenautoscroll)

BFC 的应用场景

  • 清除浮动
  • 避免某元素被浮动元素覆盖
  • 阻止外边距重叠

BFC 可以包含浮动的元素(清除浮动)

浮动元素会脱离文档流

1
2
3
4
5
<div style="border: 1px solid #427af8">
  <div style="width: 100px;height: 100px;background: #eee;float: left;"></div>
</div>
<div style="width:200px; height:200px;background: #e95;"></div>
<p>我是段段段段段段段段段段段段段段段段段段段段段段段段段段段段段落</p>

可以看到容器内元素浮动,脱离文档流,所以容器只剩下 2px border 高度。并且和容器同级的一个元素被浮动元素覆盖了。
我们试着触发容器的 BFC, 在容器上添加overflow: hidden

1
2
3
4
5
<div style="border: 1px solid #427af8;overflow: hidden;">
  <div style="width: 100px;height: 100px;background: #eee;float: left;"></div>
</div>
<div style="width:200px; height:200px;background: #e95;"></div>
<p>我是段段段段段段段段段段段段段段段段段段段段段段段段段段段段段落</p>

我们可以看到,容器包裹住了脱离文档流的元素,并且和另一个方块元素划清了界线。

避免某元素被浮动元素覆盖

来看这个栗子:

1
2
3
4
<div style="width: 100px;height: 100px;background: #eee;float: left;">左浮元素</div>
<div style="width:200px; height:200px;background: #e95;">
  我是一段被霸占家产的文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文字
</div>

我们可以看到,第一个元素左浮动,第二个元素被浮动元素覆盖,并且文字产生了环绕效果,当我们给第二元素加上overflow: hidden之后

1
2
3
4
<div style="width: 100px;height: 100px;background: #eee;float: left;">左浮元素</div>
<div style="width:200px; height:200px;background: #e95;overflow: hidden;">
  我是一段请完律师并划分财产之后的的文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文文字
</div>

这个方法可以用来实现两列自适应布局,左边的宽度固定,右边的内容自适应宽度(去掉上面右边内容的宽度)。

阻止外边距重叠

外边距合并:

1
2
3
4
5
6
<div style="width: 100px;height: 100px;background: #eee;margin-bottom: 100px;overflow: hidden;">
  我有一个向下的100px外边距
</div>
<div style="width:100px; height:100px;background: #e95;margin-top:100px;overflow: hidden;">
  我有一个向上的100px外边距
</div>

重合的 100px 合并了,如果想要避免外边距的重叠,可以将其放在不同的 BFC 容器中:

1
2
3
4
5
6
7
8
9
10
<div style="overflow: hidden;">
  <div style="width: 100px;height: 100px;background: #eee;margin-bottom: 100px;overflow: hidden;">
    我有一个向下的100px外边距和一个触发BFC的爸爸
  </div>
</div>
<div style="overflow: hidden;">
  <div style="width:100px; height:100px;background: #e95;margin-top:100px;overflow: hidden;">
    我有一个向上的100px外边距和一个触发BFC的爸爸
  </div>
</div>

有了爸爸撑腰的元素有了底气,强行把开发商划分的公共区域变成了私人区域。

以上就是BFC的全部内容了。