关于BFC

109 阅读1分钟

BFC 全称 Block Formatting Context(块格式化上下文),是 CSS 视觉渲染的独立布局区域,可理解为一个 “封闭的布局容器”—— 容器内元素按规则布局,且内外互不干扰,是解决常见布局问题的核心机制。 出现 BFC(块格式化上下文)的核心是:元素满足任一特定条件,即可触发并生成 BFC(独立的布局隔离区域),常见触发场景(即 “什么时候出现 BFC”)如下:

  1. 浮动元素触发 BFC:元素设置 float: leftfloat: right(排除 float: none)。

  2. 定位元素触发 BFC:元素设置 position: absoluteposition: fixed(脱离常规文档流,自动生成 BFC)。

  3. 特定 display 值触发 BFC:

    • display: inline-block(行内块元素)
    • display: flex / display: inline-flex(弹性布局容器)
    • display: grid / display: inline-grid(网格布局容器)
    • display: table-celldisplay: table-captiondisplay: flow-root(特殊布局场景)
  4. 溢出相关设置触发 BFC:元素设置 overflow: hiddenoverflow: autooverflow: scroll(排除 overflow: visible),是日常最常用的轻量触发方式。

如何解决


<!doctype html>
<html>
  <head>
    <style>
      .parent {
        border: 2px solid #f00;
        width: 300px;
      }
      /* 子元素浮动 */
      .child {
        float: left;
        width: 100px;
        height: 100px;
        border: 2px solid #f00;
        margin: 5px;
      }

      /* 清除浮动万能公式 */
      .clearfix::after {
        content: "";
        display: table;
        clear: both;
      }
    </style>
  </head>
  <body>
    <div class="parent clearfix">
      <div class="child">浮动元素1</div>
    </div>
  </body>
</html>