BFC、IFC、FFC、GFC 分别是什么?

CSS 中有四种格式化上下文(Formatting Context):

BFC — 块级格式化上下文

Block Formatting Context

触发条件:

overflow: hidden | auto | scroll;
display: flex | grid | inline-block | table-cell | flow-root;
position: absolute | fixed;
float: left | right;

IFC — 行内格式化上下文

Inline Formatting Context

触发条件: 块级容器中只包含行内级元素时自动创建。

/* IFC 的常见现象 */
.text-container {
  /* 默认就是 IFC */
  /* 行内元素水平排列,高度由 line-height 决定 */
}

应用:

FFC — 弹性格式化上下文

Flex Formatting Context

GFC — 网格格式化上下文

Grid Formatting Context

对比总结

类型 触发 排列方式 典型应用
BFC overflow/flex 等 垂直 清除浮动、margin 折叠
IFC 默认(行内内容) 水平 文本对齐
FFC display: flex 弹性 一维布局
GFC display: grid 网格 二维布局

其他上下文

/* 创建层叠上下文 */
.element {
  position: relative;
  z-index: 1;  /* 非 auto */
}
/* 或 */
.element {
  opacity: 0.9;
  transform: translateZ(0);
  filter: blur(0);
}

同分类其他题目