Featured image of post CSS 布局实战:Flex、Grid 与那些坑

CSS 布局实战:Flex、Grid 与那些坑

系统梳理 Flexbox 与 Grid 的核心机制,深入讲解层叠上下文、居中的六种方案、常见塌陷问题以及现代布局的实战选择。

34 次

那个永远居不中的元素

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

top: 50% 是相对父元素高度的 50%,所以元素中心在父元素中线,整体偏下半个元素的高度。

问题根源:CSS 没有「相对自身中心」的定位值。必须用 transform 补。

这个例子揭示了 CSS 布局的核心矛盾 —— 百分比永远基于父容器,而不是元素自身。

Flexbox 核心机制

Flexbox 解决的是一维布局:一个方向上排列子元素。

主轴与交叉轴

flex-direction: row     →  主轴水平,交叉轴垂直
flex-direction: column  →  主轴垂直,交叉轴水平

所有的 Flex 属性都是相对轴而言的:

主轴方向:   justify-content
交叉轴方向: align-items / align-self / align-content

这就是很多人搞混的原因 —— 记属性名没用,要记住「哪个属性管哪个轴」。

.container {
  display: flex;
  flex-direction: row;              /* 默认 */
  justify-content: center;         /* 主轴:水平居中 */
  align-items: center;             /* 交叉轴:垂直居中 */
}

六个 justify-content 值

flex-start        主轴起点对齐(默认)
flex-end          主轴终点对齐
center            主轴居中
space-between     两端对齐,中间均分间隔
space-around      每个元素两侧分配等量空间
space-evenly      每个元素周围完全等量空间

space-between vs space-around vs space-evenly 的区别(元素 3 个):

space-between:
[A]--------[B]--------[C]

space-around:
--[A]----[B]----[C]--
  (每个元素两侧各分到一半)

space-evenly:
-[A]--[B]--[C]-
  (间隔完全相等,包含两端)

完整案例:底部对齐的列表

需求:一组标签,顶部对齐,最后一个靠底部
.tags {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;   /* 每个标签内部内容底部对齐 */
  gap: 8px;
}

.tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 10px;
  background: #eef2ff;
  border-radius: 4px;
}

flex: 1 的完整含义

.item {
  flex: 1;      /* 等价于 flex: 1 1 0% */
}

flex 简写的三个值:

flex: grow shrink basis
     弹性  收缩   基准大小
flex: 1;           /* grow=1, shrink=1, basis=0%    —— 平分空间 */
flex: auto;         /* grow=1, shrink=1, basis=auto  —— 按内容大小分配 */
flex: 0 0 200px;   /* 不伸缩,固定 200px */
flex: 2;           /* 两倍于其他项的分配比例 */

经典坑:flex: 1 的 basis 是 0%,意味着内容不会撑开它。如果内容较长会溢出:

/* ❌ 内容溢出 */
.fixed { flex: 1; }              /* 基准 0,内容 500px 也不会撑开 */

/* ✅ 至少内容宽度 */
.grow { flex: 1 1 auto; }        /* 或 flex: 1 1 min-content */

常见 Flex 陷阱

陷阱一:min-width 默认值导致无法收缩

/* ❌ flex: 1 但内容不换行,导致容器被撑破 */
.item {
  display: flex;
}
.child {
  flex: 1;
  white-space: nowrap;    /* 关键问题 */
}

/* ✅ 显式设置 min-width: 0 */
.child {
  flex: 1;
  min-width: 0;           /* 允许收缩到 0 */
  overflow: hidden;       /* 超出部分隐藏 */
  text-overflow: ellipsis;
  white-space: nowrap;
}

这是 Flex 布局最常见的坑。flex item 的 min-width 默认是 auto(即内容宽度),所以它不会收缩到内容以下。

陷阱二:等分列但内容长度不同

<div class="row">
  <div class="col">短</div>
  <div class="col">很长很长很长很长很长很长很长很长的内容</div>
  <div class="col">中</div>
</div>
.col { flex: 1; }

三列等宽,但如果希望按内容比例分配:

.col:first-child { flex: 0 0 auto; }   /* 按内容 */
.col:nth-child(2) { flex: 3; }         /* 更宽 */
.col:last-child  { flex: 1; }

陷阱三:嵌套 Flex 的高度传递

.parent {
  display: flex;
  flex-direction: column;
}

.middle {
  flex: 1;
  display: flex;
  align-items: center;   /* 垂直居中 */
}

.middle 能垂直居中是因为继承了 .parent 的高度分配。但如果 .parent 的高度是 auto(由内容撑开),.middle 的 flex: 1 就失效了。

Grid 核心机制

Grid 解决的是二维布局:行列同时控制。

显式定义网格

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: auto auto;
  gap: 16px;
}

fr 单位的含义

grid-template-columns: 1fr 2fr 1fr;
/* 剩余空间按 1:2:1 分配 */

grid-template-columns: 200px 1fr 100px;
/* 固定 + 弹性 + 固定 */

fr 分配的是「剩余空间」,不是总宽度。所以混用固定值时要注意:

/* 总宽 1000px,gap 20px × 2 */
grid-template-columns: 300px 1fr;
/* fr 部分 = 1000 - 300 - 40(gap) = 660px */

响应式无需媒体查询

Grid 最强的特性:

/* 自动填充:最少 250px,能放几列放几列 */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

/* 自动适应:尽量填满,放不下就换行 */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

auto-fill vs auto-fit:

容器 1000px,每项 minmax(250px, 1fr)

auto-fill: 放 4 个(空列保留,每列 240px)
auto-fit:   放 4 个(空列合并,每列 250px)

效果看起来一样,但:
  项目数量少于能放的数量时,差异明显

这套写法替代了 90% 的媒体查询:

/* 不需要为每个断点写媒体查询 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 1.5rem;
}

/* 手机上自然变成 1 列,平板 2 列,桌面 3-4 列 */

区域命名:可视化布局

.layout {
  display: grid;
  grid-template-areas:
    "header header header"
    "sidebar main   main"
    "footer footer footer";
  grid-template-columns: 200px 1fr 1fr;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main   { grid-area: main; }
.footer { grid-area: footer; }

响应式版本:

@media (max-width: 768px) {
  .layout {
    grid-template-areas:
      "header"
      "main"
      "sidebar"
      "footer";
    grid-template-columns: 1fr;
  }
}

Grid 定位:不像 Flex 那样依赖源顺序

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.item-1 { grid-column: 1 / 3; }   /* 占第 1-2 列 */
.item-2 { grid-row: 1 / 3; }      /* 占第 1-2 行 */
.item-3 { grid-column: 2 / -1; }  /* 从第 2 列到最后 */

这是 Flex 做不到的 —— Flex 里元素的顺序由 DOM 决定,Grid 可以自由摆放。

六种水平垂直居中方案

方案一:Flex(最常用)

.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

推荐:语义清晰,两轴都居中。

方案二:Grid

.center {
  display: grid;
  place-items: center;   /* 等价于 align-items + justify-items */
}

place-items 是 Grid 的简写,写法最简洁。

方案三:绝对定位 + transform

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

适用于脱离文档流的元素(模态框、气泡提示)。父容器需要 position: relative。

方案四:Grid 的 place-content

.container {
  display: grid;
  place-content: center;   /* 整个内容块居中 */
}

方案五:padding + 行高(旧方案,不推荐)

<div class="center">单行文本</div>
.center {
  height: 200px;
  line-height: 200px;
  text-align: center;
}

只适用于单行文本,多行会失效。

方案六:margin auto(仅块级水平居中)

.block {
  width: 300px;
  margin: 0 auto;    /* 水平居中 */
}

只能水平,不能垂直(因为垂直方向没有「剩余空间」的概念)。

层叠上下文:z-index 失效的常见原因

z-index 只在层叠上下文内有效。

什么会创建层叠上下文

① 根元素(html)
② position 非 static 且 z-index 不为 auto 的元素
③ opacity < 1 的元素
④ transform / filter / perspective 不为 none 的元素
⑤ flex/grid 项且 z-index 不为 auto
⑥ will-change: transform / opacity
⑦ position: sticky
⑧ mix-blend-mode 不为 normal

典型问题:transform 创建了新的上下文

<div class="parent">       <!-- z-index: 10 -->
  <div class="child">      <!-- z-index: 9999 -->
    文字
  </div>
</div>
<div class="sibling"></div>  <!-- z-index: 5 -->
.parent {
  position: relative;
  z-index: 10;
}
.child {
  position: absolute;
  z-index: 9999;      /* ❌ 无效!受限于 .parent 的上下文 */
}
.sibling {
  position: absolute;
  z-index: 5;         /* 仍然盖在 .parent 之上 */
}

原因:.parent 的 z-index:10 创建了层叠上下文,.child 的 9999 只在这个上下文内部排序,无法超越 .parent 的整体层级。

解决:把 z-index 提到正确层级

<div class="parent">
  <div class="child">文字</div>
</div>
<div class="sibling"></div>
.parent {
  position: relative;
  /* 不设置 z-index,或者设成想要的层级 */
}
.child {
  position: absolute;
  z-index: 20;      /* 直接提升到需要的高度 */
}
.sibling {
  position: absolute;
  z-index: 5;
}

检查层叠上下文

// Chrome DevTools:Layers 面板
// 可以直接看到每个元素所在的层叠上下文

// 或者用这个脚本检测
function findStackingContext(el) {
  const styles = getComputedStyle(el)
  const reasons = []

  if (styles.zIndex !== 'auto') reasons.push(`z-index: ${styles.zIndex}`)
  if (parseFloat(styles.opacity) < 1) reasons.push(`opacity: ${styles.opacity}`)
  if (styles.transform !== 'none') reasons.push(`transform: ${styles.transform}`)
  if (styles.filter !== 'none') reasons.push(`filter: ${styles.filter}`)
  if (styles.position === 'sticky') reasons.push('position: sticky')
  if (styles.willChange !== 'auto') reasons.push(`will-change: ${styles.willChange}`)
  if (styles.isolation === 'isolate') reasons.push('isolation: isolate')

  return reasons
}

高度塌陷与 margin 折叠

高度塌陷

<div class="parent">
  <div class="child">内容</div>
</div>
/* parent 没有高度,child 的 margin-top 会「穿透」出去 */
.parent { background: #eee; }
.child { margin-top: 20px; }

结果:.parent 顶部被顶下 20px,但自身高度为 0。

解决方案:

/* 方案 1:BFC(最常用) */
.parent { overflow: hidden; }        /* 或 auto/scroll */

/* 方案 2:Flex */
.parent { display: flex; flex-direction: column; }

/* 方案 3:Grid */
.parent { display: grid; }

/* 方案 4:伪元素清除 */
.parent::after {
  content: '';
  display: block;
  clear: both;
}

/* 方案 5:padding 代替 margin(治标) */
.child { margin-top: 20px; }
.parent { padding-top: 1px; margin-top: -1px; }

BFC 的价值:BFC(块级格式化上下文)内部元素的 margin 不会影响外部,内部的浮动也会被包含。

margin 折叠

相邻块级元素的垂直 margin 会折叠成最大值,而不是相加:

<div class="box1">A</div>
<div class="box2">B</div>
.box1 { margin-bottom: 30px; }
.box2 { margin-top: 20px; }
/* 实际间距 = 30px,不是 50px */

这经常导致「我想设置 10px 间距却得到 15px」的困惑。

阻止折叠的方法:

/* 给容器加 padding 或 border */
.container {
  padding: 1px;        /* 或 border: 1px solid transparent */
  overflow: hidden;    /* 或 display: flex */
}

Flex 容器的子元素 margin 不会折叠 —— 这是用 Flex 布局的一个附带好处。

定位方式对比

定位参照物是否脱离文档流
static无(默认)否
relative自身原位置否(保留占位)
absolute最近的定位祖先是
fixed视口是
sticky滚动容器否(混合模式)

sticky 的正确用法

/* ❌ 不生效:父容器没有设置高度限制 */
.header {
  position: sticky;
  top: 0;
}

/* ✅ sticky 需要一个「滚动容器」 */
.scroll-container {
  height: 100vh;      /* 明确高度 */
  overflow-y: auto;   /* 滚动容器 */
}

.header {
  position: sticky;
  top: 0;             /* 相对滚动容器 */
  z-index: 100;
}

sticky 失效的常见原因:

① 父元素有 overflow: hidden/auto/scroll
   → overflow 不是 visible 会创建新的滚动容器,sticky 的参照变了
② 父元素没有明确的 height/min-height
③ 祖先元素有 transform(会创建包含块)
④ 没有设置 top/bottom/left/right 中的至少一个

实战:几种常见布局

卡片网格

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.card {
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.card-body {
  flex: 1;              /* 占满剩余高度 */
  padding: 16px;
}

.card-text {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

组合了 Grid(外层分列)+ Flex(卡片内部纵向布局)+ line-clamp(文本截断)。

全屏布局

.app {
  display: grid;
  grid-template-rows: auto 1fr auto;   /* 头 / 主 / 脚 */
  grid-template-areas:
    "header"
    "main"
    "footer";
  min-height: 100vh;
}

main {
  grid-area: main;
  overflow-y: auto;       /* 只让主内容区滚动 */
}

header, footer {
  position: sticky;
  top: 0;
  z-index: 10;
}

侧边栏布局

.layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr) minmax(0, 300px);
  gap: 32px;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
}

@media (max-width: 1024px) {
  .layout { grid-template-columns: 1fr; }
}

minmax(0, 1fr) 而不是 1fr —— 防止 Grid 项内容过长时撑破布局(与 Flex 的 min-width: 0 同理)。

现代 CSS 特性

aspect-ratio:固定宽高比

.thumbnail {
  aspect-ratio: 16 / 9;
  object-fit: cover;
  width: 100%;
}

替代了以前的 padding-top 百分比技巧。

gap 终于支持 Flex 和 Grid 之外的场景

/* 现在 block 布局也支持 gap(现代浏览器) */
.container {
  display: block;
  gap: 16px;          /* ✅ 以前不管用 */
}

:has() 父级选择器

/* 有子元素的项才显示边框 */
.item:has(img) {
  padding-top: 56.25%;
  background-size: cover;
}

/* 表单验证的样式反馈 */
.input:has(+ .error) {
  border-color: red;
}

:has() 是 CSS 最有用的新特性之一,可以在不写 JS 的情况下根据内容改变样式。

clamp():响应式字号

h1 {
  /* 最小 24px,理想 4vw,最大 48px */
  font-size: clamp(24px, 4vw, 48px);
}

.container {
  padding: clamp(16px, 3vw, 48px);
}

不需要媒体查询就能实现平滑的响应式字号。

容器查询

.card-container {
  container-type: inline-size;
}

/* 根据容器宽度而不是视口宽度响应 */
@container (min-width: 400px) {
  .card { display: grid; grid-template-columns: 150px 1fr; }
}

组件不再依赖视口大小,真正做到「组件级响应式」。

选择器的坑

优先级计算

/* 优先级:id > class/属性/伪类 > 标签 > 通配符 */
#header .nav > ul li a.active { }

/* (0, 3, 2, 1) → 3个class/伪类,2个标签,1个id */

!important 是最后的手段,滥用会导致维护困难:

/* ❌ 尽量避免 */
color: red !important;

/* ✅ 用 CSS 变量或者提高选择器特异性 */
.app.theme-dark .header { color: white; }

选择器的性能

性能排序(从好到差):

#header                    → 最好(id 直接定位)
.header                    → 好(单个 class)
.header .nav               → 一般(两个 class)
.header .nav > ul li a     → 差(后代选择器,浏览器要遍历)
*                          → 最差

深层嵌套的选择器会拖慢渲染,尤其在 DOM 很大时。

nth-child 的陷阱

/* 第 2、4、6...个偶数项 */
li:nth-child(even) { background: #f5f5f5; }

/* ❌ 想选中「第 2 个 li 之后的所有 li」但写错了 */
li:nth-child(n+2) { color: red; }

/* 选中所有非首项 */
li:not(:first-child) { margin-left: 16px; }

/* 只在有多个子元素时才应用(罕见但有用) */
li:only-child { background: yellow; }

调试技巧

// 检测元素是否溢出(水平滚动条的常见原因)
document.querySelectorAll('*').forEach(el => {
  if (el.scrollWidth > el.clientWidth) {
    console.warn('水平溢出:', el.className, el.scrollWidth, el.clientWidth)
  }
})

// 找出所有层叠上下文
document.querySelectorAll('*').forEach(el => {
  const s = getComputedStyle(el)
  if (s.zIndex !== 'auto' || s.transform !== 'none' || parseFloat(s.opacity) < 1) {
    console.log('层叠上下文:', el.className)
  }
})

// 可视化所有盒模型
document.documentElement.style.cssText += `
  * { outline: 1px solid rgba(255,0,0,0.2); }
  *:hover { outline: 1px solid rgba(0,128,255,0.5); }
`

Chrome DevTools 快捷键:

Ctrl+Shift+C    元素选择器(按住可查看盒模型)
Ctrl+Shift+P    命令面板
?              快捷键速查

Chrome 里设置 Grid overlay:

选中容器 → Styles 面板 → grid-template-rows 图标
→ 可以看到网格线

上线检查清单

【响应式】
□ 用 Grid 的 auto-fill/auto-fit 而非写死列数
□ 用 clamp() 做流式字号
□ 图片设置了 aspect-ratio 或明确宽高
□ 移动端无水平滚动

【Flex】
□ 可收缩的项设置了 min-width: 0
□ 弹性项理解了 flex-basis 的影响
□ 静态配置不用 flex(用 Grid 或 block 更合适)

【Grid】
□ 列定义用 minmax(0, 1fr) 防止溢出

【层叠】
□ 没有滥用 z-index
□ 理解了 transform/opacity 会创建层叠上下文
□ 用 Layers 面板验证过

【其他】
□ 容器清除浮动(或用 Flex/Grid)
□ 理解了 margin 折叠的规则
□ sticky 的父容器设置了正确的高度和 overflow

最后

布局方案的选择可以简化成三句话:

一维排列              → Flex
二维排列 / 整体栅格   → Grid
需要绝对精确的定位    → absolute + transform

现代 CSS 的三个特性值得优先学习:

  1. Grid 的 auto-fit —— 消灭大部分媒体查询
  2. clamp() —— 流式排版,无需断点
  3. :has() —— 纯 CSS 实现条件样式

这三条用熟之后,你的 CSS 会从「一堆补丁」变成「结构清晰」。