DrillLab
第 8 / 105 道8 / 105 · #273

Flexbox vs Grid

Flexbox vs Grid

先自己答,再往下看Answer it yourself first

一句话:Flex 是一维的 (一行或一列,内容驱动); Grid 是二维的(同时管行和列,布局驱动)。

怎么选,一个判断句就够:「我需要同时控制行和列的对齐吗?」 要 → Grid;不要 → Flex。

FlexGrid
维度一维二维
谁决定尺寸内容(子项说我要多大)容器(我先划好格子,你往里放)
典型场景导航栏、按钮组、卡片内部的图文排列、 「左边文字右边按钮」整页骨架(头/侧栏/主体/脚)、 商品瀑布流、日历、表单的标签列 + 输入列
缺口flex-wrap 换行后各行互不知道对方,对不齐要先想清楚格子,改结构比 Flex 麻烦

会追问:「能一起用吗?」——正常做法就是一起用: Grid 搭页面骨架,每个格子内部用 Flex 排内容。 答「二选一」反而显得没实战过。

还会追问 flex: 1 是什么:它是三个属性的简写 ——flex-grow: 1; flex-shrink: 1; flex-basis: 0%。 意思是「剩余空间我来占,需要时也可以被压缩, 初始尺寸按 0 算」。 这就是「一个固定宽侧栏 + 一个自适应主体」最短的写法。

In one line: Flex is one-dimensional (a row or a column, content-driven); Grid is two-dimensional (rows and columns together, layout-driven).

One sentence decides it: “Do I need to control alignment across rows and columns at once?” Yes → Grid. No → Flex.

FlexGrid
DimensionsOneTwo
Who decides sizeThe content (items say how big they are)The container (cells first, content after)
Typical useNav bars, button groups, image-plus-text inside a card, “text left, button right”Page skeleton (header / sidebar / main / footer), product grids, calendars, label-column plus input-column forms
WeaknessAfter flex-wrap, rows know nothing about each other, so nothing lines upYou must plan the cells; restructuring is more work

Follow-up: “Can you use both?” — using both is the normal answer: Grid for the page skeleton, Flex for the contents of each cell. Saying “pick one” suggests you have not shipped much.

They will also ask what flex: 1 means: it is shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0% — “I take the leftover space, I may be compressed, and my starting size counts as zero”. That is the shortest way to write “fixed sidebar plus fluid main area”.

CSS实际项目里的分工示意Illustrative
1/* Grid 搭骨架 */
2.layout {
3 display: grid;
4 grid-template-columns: 240px 1fr; /* 侧栏固定,主体吃剩下的 */
5 grid-template-rows: 56px 1fr;
6 min-height: 100vh;
7}
8
9/* 格子内部用 Flex 排内容 */
10.topbar {
11 display: flex;
12 align-items: center;
13 justify-content: space-between;
14 gap: 12px;
15}
16
17/* 「固定宽 + 自适应」的经典两行 */
18.sidebar { flex: 0 0 240px; } /* 不长不缩,就 240 */
19.content { flex: 1; } /* 剩下全归我 */
1/* Grid for the skeleton */
2.layout {
3 display: grid;
4 grid-template-columns: 240px 1fr; /* sidebar fixed, main takes the rest */
5 grid-template-rows: 56px 1fr;
6 min-height: 100vh;
7}
8
9/* Flex for the content inside a cell */
10.topbar {
11 display: flex;
12 align-items: center;
13 justify-content: space-between;
14 gap: 12px;
15}
16
17/* The classic two lines for "fixed width plus fill the rest" */
18.sidebar { flex: 0 0 240px; } /* never grows, never shrinks, stays 240 */
19.content { flex: 1; } /* takes everything that is left */