BFC 介绍

简介

块格式化上下文 是块级盒子在布局过程中发生的区域。

作用: 形成独立的渲染区域, 使得内部元素的渲染不会影响到外界。

以下方式可以创建 BFC:

  • 根元素 html
  • 浮动元素 (float 不是 none)
  • 绝对定位元素 (positionfixedabsolute)
  • display 值为 inline-block, flow-root的元素。
  • 表格相关的元素(即displayinline-table, table, table-row, table-row-group, table-header-group, table-footer-group, table-cell, table-caption)。
  • overflow 不是 visibleclip 的块元素
  • 弹性元素或网格元素的 直接子元素 (当该子元素不是 flex, grid, table 时)
  • contain 值为 layout, content, paint 的元素
  • 多列容器(column-countcolumn-width值不为auto
  • column-spanall 的元素

应用

包含内部浮动元素

<div id="basic" style="background: blue;">  <div style="float: left; margin-top: 3px; background: red;">    float: left; margin-top: 3px; background: red;  </div>  <div>background:blue;</div></div>

如上述情况, #basic 中的第一个 div 设置了 float, 其脱离了文档流。因此, 其尺寸不会影响到 #basic

要使得浮动元素不溢出父容器,可以在父容器创建 bfc。如 #bfc:

<div id="bfc" style="background: blue; display: flow-root;">  <div style="float: left; margin-top: 3px; background: red;">    float: left; margin-top: 3px; background: red;  </div>  <div>background:blue; display: flow-root;</div></div>

其结果如下:

排除外部浮动元素

上面的解决方案还有一个问题,父容器的另外一个子元素会把浮动元素包含进去。如果需要排除该浮动元素,可以在这个子元素中也创建 BFC

<div style="display: flow-root; background: blue;">  <div style="float: left; margin-top: 10px; background: red;">    float: left; margin-top: 10px; background: red;  </div>  <div style="background: green;">child</div></div>

变成:

<div style="display: flow-root; background: blue;">  <div style="float: left; margin-top: 10px; background: red;">    float: left; margin-top: 10px; background: red;  </div>  <div style="background: green; display: flow-root;">child</div></div>

其结果如下:

阻止 margin 重叠

在默认情况下,两个相邻元素的margin会重叠在一起。如果想要阻止该情况,可以用一个具有 BFC 的父容器包裹其中一个元素。

<section>  <div style="background:black;margin:10px;width:88px;height:88px;"></div>  <div style="background:black;margin:10px;width:88px;height:88px;"></div></section>

改成

<section>  <div style="background:black;margin:10px;width:88px;height:88px;"></div>  <div style="display:flow-root;">    <div style="background:black;margin:10px;width:88px;height:88px;"></div>  </div></section>

其结果如下:

关联概念

  • Inline Formatting Context
  • Flex Formatting Context
  • Grid Formatting Context

引用