CSS 现代布局:Grid、容器查询与 :has()
MrSmy Lv5

做了七年后台系统,我对 CSS 的认识变了三次:先是”用 float 和 clearfix”,再是”flex 一把梭”,现在是”看场景选 Grid 还是 flex”。

这篇讲三个真正改变了写法的特性:Grid 的二维布局、容器查询带来的组件自治、**:has() 解决的”父选子”**。

Grid vs Flex:不是替代关系

最常见的误解是”Grid 比 flex 新,所以用 Grid”。它们解决的是不同问题:

Flex Grid
维度 一维(行或列) 二维(行和列)
内容驱动 内容决定尺寸 容器决定轨道
典型场景 导航、按钮组、表单行 页面骨架、卡片网格、对齐的表格
子元素换行 只能单行或 flex-wrap 天然的 grid-template-areas

判断标准:如果”某一行的高度需要由另一行的内容决定”,就该用 Grid。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 经典后台布局:侧栏固定 + 主区自适应 + 上下通栏 */
.layout {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: 56px 1fr;
grid-template-areas:
"header header"
"aside main";
height: 100vh;
}

.header { grid-area: header }
.aside { grid-area: aside; overflow: auto }
.main { grid-area: main; overflow: auto }

grid-template-areas 是 Grid 最被低估的能力——布局写成了 ASCII 图,看一眼就知道结构。这比 flex + 一堆嵌套容器好维护得多。

minmax + auto-fit:自适应的卡片网格

以前写响应式卡片网格要配多个断点:

1
2
3
4
5
/* 老写法 */
.cards { display: flex; flex-wrap: wrap; gap: 16px }
.card { width: calc(33.333% - 11px) }
@media (max-width: 900px) { .card { width: calc(50% - 8px) } }
@media (max-width: 600px) { .card { width: 100% } }

现在一行:

1
2
3
4
5
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 16px;
}

含义:每列最少 280px,能塞几列塞几列,剩余空间平均分。

auto-fit 和 auto-fill 的区别很关键:

1
2
3
4
5
/* auto-fill:空轨道保留,项目不会被拉伸 */
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));

/* auto-fit:空轨道折叠,项目撑满容器 */
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));

容器宽 1200px、项目只有 2 个:

  • auto-fill → 4 个轨道,2 个项目占前两个,右边空出一半
  • auto-fit → 2 个轨道,各 592px

**只有 1-2 个项目时用 auto-fit,项目数量动态且可能不足时才需要 auto-fill**(比如要保留占位)。

subgrid:跨容器对齐

这是 Grid 长期缺失的一块,2023 年底才在三大浏览器都可用。

问题场景:卡片列表,每张卡片有”标题、描述、价格、按钮”,希望所有卡片的”价格”在同一水平线上:

1
2
3
4
5
6
7
8
9
10
11
.card {
display: grid;
grid-template-rows: subgrid;
grid-row: span 4; /* 占父 grid 的 4 行 */
}

.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
grid-template-rows: repeat(4, auto); /* 定义 4 条行轨道 */
}

subgrid 让子元素的轨道继承父级,于是四行的高度在所有卡片间共享——标题长的卡片会把所有卡片的标题行都撑高,价格自然对齐。

以前这要靠 flex: 1 撑中间 + margin-top: auto 推按钮到底部,能对齐底部但对齐不了中间行。

兼容性注意:Safari 16 之前不支持,需要 @supports 降级:

1
2
3
4
5
6
7
@supports (grid-template-rows: subgrid) {
.card { display: grid; grid-template-rows: subgrid; grid-row: span 4 }
}
@supports not (grid-template-rows: subgrid) {
.card { display: flex; flex-direction: column }
.card__button { margin-top: auto }
}

容器查询:组件不再关心视口

这是过去两年最大的写法变化。

老问题:一个 Card 组件,在”侧栏里”要竖排、在”主区域”要横排。但组件不知道自己被放在哪:

1
2
3
4
/* 媒体查询只能看视口,不能看容器 */
@media (min-width: 768px) {
.card { flex-direction: row } /* 侧栏里也是 row,错了 */
}

容器查询让组件按”父容器宽度”响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.card-wrapper {
container-type: inline-size;
container-name: card;
}

@container card (min-width: 480px) {
.card {
flex-direction: row;
gap: 16px;
}
.card__title { font-size: 18px }
}

@container card (max-width: 479px) {
.card {
flex-direction: column;
}
.card__title { font-size: 16px }
}

同一个 Card 组件,放进侧栏(300px)自动竖排,放进主区(800px)自动横排,不需要任何 prop、不需要 useMediaQuery。

这带来的架构变化很大:

媒体查询 容器查询
响应依据 视口 组件所在容器
组件复用 需要”传 breakpoint” 零配置
页面布局调整 组件可能被压坏 自动适应
单元测试 要 mock 视口 可直接设容器宽度

我们迁移后的实际收益:Card / Table / Chart 三个组件里删掉了 9 个 isCompact / isNarrow 之类的 prop,组件 API 变干净了。

容器查询的三个实用细节

1. container-type: inline-size 会创建一个”包含块”

里面的 position: fixed 元素会相对它定位(而不是视口)。这个坑很隐蔽——某次弹窗突然只覆盖了卡片区域,查了半天。

如果只是想要响应式不想影响定位,用 container-type: inline-size 配合不在里面放 fixed 元素,或者把弹窗渲染到 document.body(Portal)。

2. 单位 cqw / cqh / cqi

1
2
3
.card__title {
font-size: clamp(16px, 4cqi, 24px); /* 容器宽度的 4%,限制在 16-24px */
}

这是”组件内部的流体字号”,比 vw 好——vw 跟着视口走,组件放到侧栏里就完蛋。

3. 容器查询不能”向上”影响容器本身

1
2
3
4
/* 这是无效的:容器查询只能作用于容器内的元素 */
@container card (min-width: 480px) {
.card-wrapper { padding: 24px } /* 不生效 */
}

要改容器自身样式,只能靠 @media 或者用负向思路(在容器内部加一层 wrapper)。

:has():终于能”父选子”

CSS 选择器一直是”向下”的,父:has(子) 补上了最后一块。

场景 1:表单错误时给字段整体加边框

以前:

1
2
3
4
<div className={cx('field', { 'field--error': errors.email })}>
<input />
{errors.email && <span className="error">{errors.email}</span>}
</div>

现在纯 CSS:

1
2
3
4
.field:has(.error) {
border-color: #e5484d;
background: #fff5f5;
}

不需要把错误状态提升到父组件的 className。

场景 2:有图的卡片与无图的卡片布局不同

1
2
3
4
5
6
.card:has(img) {
grid-template-columns: 120px 1fr;
}
.card:not(:has(img)) {
padding: 16px;
}

场景 3:选中数量决定按钮状态

1
2
3
.list:has(input:checked) .bulk-actions {
display: flex;
}

“只要有任意一项被勾选,就显示批量操作栏”——一行 CSS,不用监听 onChange。

场景 4:修复”最后一个有内容的子元素”

1
2
3
4
/* 有内容的 .item 才计算 */
.item:not(:has(*:not(:empty))) {
display: none;
}

性能注意::has() 是反向匹配,浏览器优化程度不如普通选择器。大列表里写 .list:has(.item:hover) .toolbar 这种会有性能问题。

原则:**:has() 用在”状态挂载”(表单、选中、展开)上,不要用在滚动/悬停这类高频变化上**。

兼容性:Chrome 105+ / Safari 15.4+ / Firefox 121+。2024 年可以说”基本可用”,但需要给老浏览器留降级(@supports selector(:has(*)))。

逻辑属性:为国际化留的余地

1
2
3
4
5
6
7
/* 物理属性 */
margin-left: 16px;
padding-right: 8px;

/* 逻辑属性 */
margin-inline-start: 16px;
padding-inline-end: 8px;

在 dir="rtl" 的文档里,逻辑属性会自动镜像。中文项目看起来”用不上”,但一旦要做阿拉伯语,物理属性要改上千行。

我们的做法:新代码统一用逻辑属性(margin-inline-start),老代码不动。

对应的简写:

物理 逻辑
margin-left/right margin-inline-start/end
margin-top/bottom margin-block-start/end
width inline-size
height block-size
left/right inset-inline-start/end

:is() 与 :where():减少选择器重复

1
2
3
4
5
6
7
8
9
/* 以前 */
.card h1, .card h2, .card h3, .card h4 {
margin-top: 0;
}

/* 现在 */
.card :is(h1, h2, h3, h4) {
margin-top: 0;
}

:is() 的特异性取最高的那个,:where() 的特异性为 0:

1
2
3
4
5
/* :where 特异性 0,任何规则都能覆盖它 —— 适合写基础样式 */
:where(ul, ol) {
padding-left: 0;
list-style: none;
}

这解决了”reset 样式特异性太高,后面覆盖不掉”的老问题。

一个完整的重构对比

一个后台列表页,从”flex + 媒体查询”改到”Grid + 容器查询”:

改造前(3 个断点 + 一堆 className):

1
2
3
4
5
6
7
8
<div className={cx('page', { narrow: isNarrow })}>
<aside className={cx('side', { collapsed: isNarrow })}>...</aside>
<main>
<div className={cx('cards', { narrow: isNarrow })}>
{items.map((i) => <Card key={i.id} compact={isNarrow} item={i} />)}
</div>
</main>
</div>

改造后(0 个断点):

1
2
3
4
5
6
7
8
<div className="page">
<aside className="side">...</aside>
<main>
<div className="cards">
{items.map((i) => <Card key={i.id} item={i} />)}
</div>
</main>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.page {
display: grid;
grid-template-columns: minmax(180px, 240px) 1fr;
min-height: 100vh;
}
@media (max-width: 720px) {
.page { grid-template-columns: 1fr }
}

.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 12px;
}

/* Card 内部的适配全靠容器查询 */
.card-wrapper { container-type: inline-size }
@container (min-width: 320px) { .card { flex-direction: row } }

代码量:JSX 减 40%,CSS 减 30%,同时侧栏折叠时卡片自动变成紧凑布局,不需要 JS 通知。

踩过的坑

坑 1:grid 里的 overflow: auto 必须配 min-height: 0

1
2
3
4
.main {
grid-area: main;
overflow: auto; /* 不起作用,因为 min-height 默认是 auto */
}

Grid/Flex 子项的 min-height 默认是 auto(不缩小到内容以下),所以 overflow 不会被触发。必须:

1
2
3
4
5
.main {
grid-area: main;
overflow: auto;
min-height: 0; /* 或 min-block-size: 0 */
}

这是我在 flex 和 grid 里踩过最多的一个坑。

坑 2:aspect-ratio 与 grid 的隐式行高冲突

1
2
.grid { display: grid; grid-template-columns: repeat(3, 1fr) }
.grid img { aspect-ratio: 16 / 9; width: 100% }

看起来没问题,但如果某张图加载失败(alt 文字撑高),整行会比预期高。用 object-fit: cover + 固定 height 更稳。

坑 3:gap 在打印样式里会变成空白

PDF 导出时 gap 的行为在各浏览器不一致。打印样式建议改回 margin。

坑 4:container-type 会让 position: sticky 失效

如果祖先有 container-type,sticky 子元素的滚动祖先可能不是你预期的那个。

小结

现代 CSS 的写法变化,可以归成三条:

  1. 布局交给 Grid,内容流交给 Flex。grid-template-areas 让骨架一眼可读,minmax + auto-fit 省掉断点,subgrid 解决跨卡片对齐。
  2. 容器查询让组件自治。组件只看自己有多宽,不再需要 isNarrow 之类的 prop,也不再被”这里放 sidebar、那里放 main”搞坏。
  3. :has() / :is() / :where() 让选择器表达力追上需求。状态挂载不再需要 JS 把 className 提上去,基础样式也不再被特异性卡住。

最后提醒:不要为了用新特性而重写。我们只在”新写的组件”和”确实有痛的布局”上迁移,老代码留着反而更安全。

  • 本文标题:CSS 现代布局:Grid、容器查询与 :has()
  • 本文作者:MrSmy
  • 创建时间:2024-01-21 21:08:00
  • 本文链接:https://fengyang.live/2024/01/21/CSS现代布局:Grid、容器查询与has/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!