【 CSS 】BFC

95 阅读1分钟

块格式化上下文,CSS2.1中添加

直观表达即:对一个元素设置为BFC后,它就成为了一个独立的单位,不会干扰别人,对应的子元素也不会受外界环境干扰。

一、怎样形成BFC?

默认根元素(html 元素)会创建一个 BFC,除此以外,下面的任何一个条件都可以创建一个新的 BFC:

  • 设置非 float: none (默认) 的浮动
  • 设置非 overflow: visible (默认) 控制内容溢出元素框时显示的方式
  • 设置非 position:static(默认) / relative 的定位类型
  • 设置display:inline-block / table-cell / table-caption 为任何一个

不干扰别人,也不受外界干扰,看看它的能力😆

二、BFC作用场景?

1)自适应的两栏布局

<div>
  <div style="float:left; width:100px;height:100px">1</div>
  <div style="overflow:hidden; height:200px">1</div>
</div>

256467754-d8dd0e95-991c-4bf0-9e94-dd43f577a522.png 触发BFC:

256467857-1d54ef5d-d250-4680-a9ef-22725ff58a6a.png

2)消除兄弟元素之间的margin重叠

<p style="margin: 50px 0">1</p>
<p style="overflow: auto">
  <p style="margin: 50px 0">1</p>
</p>

256467959-978f1fef-497d-45f0-afb2-2bb7819d8bd8.png 触发BFC:

256468001-61859294-c1fd-43b6-b429-58fc4bd6f026.png 3)去除浮动

<div style="overflow:auto;border:1px solid red">
  <div style="float:left;width:100px;height:100px">1</div>
  <div style="float:left;width:100px;height:100px">1</div>
</div>

256468156-5a0e8aa4-acf7-44f1-8141-92de32bfd3a1.png 触发BFC:

256468214-f41752e3-8f69-470c-95f4-3c879ddb9e85.png


拓展:

CSS2.1 中只有 BFC 和 IFC, CSS3 中还增加了 GFC 和 FFC ( 查了IFC, 看了半天懵里懵懂,暂且搁置 )

IFC(Inline Formatting Contexts)直译为"内联格式化上下文"

GFC(GridLayout Formatting Contexts)直译为"网格布局格式化上下文"

FFC(Flex Formatting Contexts)直译为"自适应格式化上下文"