一、BFC
BFC (Block Formatting Context) 即块格式化上下文,它是一个独立的布局环境,其中的元素不受外界的影响。
要搞清楚 BFC 的作用,我们先来看下面几个问题。
二、margin 坍塌问题
同级元素垂直方向上的坍塌(水平方向上不会坍塌),比如:上面的元素设置了 margin-bottom,下面的元素设置了 margin-top,这种情况下,会按照较大者去显示。
来看下面这个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13
   | <body>      <div class="test"></div>      <div class="test"></div>  </body>    .test {      width: 200px;      height: 200px;      margin: 50px;      padding: 50px;      border: 50px solid black;      background-color: brown;  }
   | 
 

修改代码解决问题:
1 2 3 4 5 6 7 8 9 10
   | .container {    overflow: hidden;  }   <div class="container">    <div class="test"></div>  </div>  <div class="container">    <div class="test"></div>  </div>
  | 
 
父子元素之间的坍塌,也是垂直方向上会坍塌,水平方向上不会坍塌。比如:父元素设置了 margin-top,子元素也设置了 margin-top,这种情况下,会按照较大者去显示,或者只设置子元素的 margin-top,那么父元素会随子元素一起掉下来。
例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | .father {    width: 300px;    height: 300px;    margin-top: 50px;    margin-left: 50px;    background-color: brown;  }  .son {    width: 100px;    height: 100px;    margin-top: 60px;    margin-left: 60px;    background-color: black;  }    <body>      <div class="father">          <div class="son"></div>      </div>  </body>
  | 
 

修改代码解决问题:
1 2 3 4 5 6 7 8 9
   | .container {    overflow: hidden;  }
  <div class="father">    <div class="container">      <div class="son"></div>    </div>  </div>
  | 
 
三、浮动塌陷问题
元素设置了 float 之后会,会脱离文档流,原本父元素会包裹住子元素,但是子元素脱离了文档流,所以子元素就会变成未被父元素包裹的样子,父元素本应该被撑开的高度也会坍塌。
1 2 3 4 5 6 7 8 9 10 11 12 13
   | .container {    border: 1px solid red;  }  .test {    width: 100px;    height: 100px;    background-color: blue;    float: left;  }    <div class="container">    <div class="test"></div>  </div>
  | 
 
显示效果如下图所示:

修改代码解决问题:
1 2 3 4
   | .container {    border: 1px solid red;  + overflow: hidden;  }
  | 
 
四、浮动元素覆盖问题
一个元素设置了浮动,另一个元素未设置浮动,浮动元素会覆盖未添加浮动的元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | .test1 {    width: 100px;    height: 100px;    background-color: blue;    float: left;  }  .test2 {    width: 200px;    height: 200px;    background-color: red;  }    <div class="test1"></div>  <div class="test2"></div>
  | 
 
显示效果如下图所示:

修改代码解决问题:
1 2 3 4 5 6
   | .test2 {   width: 200px;   height: 200px;   background-color: red; + overflow: hidden; }
  | 
 
五、总结
1. BFC 的作用
- 解决 margin 塌陷问题
 
- 清除浮动
 
- 阻止元素被浮动元素覆盖
 
2. BFC 如何创建
- 根元素(
<html>) 
- 浮动元素(元素的 float 不是 none)
 
- 绝对定位元素(元素的 position 为 absolute 或 fixed)
 
- display 为 inline-block、table-cell、table-caption、table、table-row、table-row-group、table-header-group、table-footer-group、inline-table、flow-root、flex 或 inline-flex 或 inline-grid
 
- overflow 值不为 visible 的块元素
 
- contain 值为 layout、content 或 paint 的元素
 
- 多列容器(元素的 column-count 或 column-width 不为 auto,包括 column-count 为 1)