Flexbox vs Grid
Flexbox vs Grid
一句话:Flex 是一维的 (一行或一列,内容驱动); Grid 是二维的(同时管行和列,布局驱动)。
怎么选,一个判断句就够:「我需要同时控制行和列的对齐吗?」 要 → Grid;不要 → Flex。
| Flex | Grid | |
|---|---|---|
| 维度 | 一维 | 二维 |
| 谁决定尺寸 | 内容(子项说我要多大) | 容器(我先划好格子,你往里放) |
| 典型场景 | 导航栏、按钮组、卡片内部的图文排列、 「左边文字右边按钮」 | 整页骨架(头/侧栏/主体/脚)、 商品瀑布流、日历、表单的标签列 + 输入列 |
| 缺口 | 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.
| Flex | Grid | |
|---|---|---|
| Dimensions | One | Two |
| Who decides size | The content (items say how big they are) | The container (cells first, content after) |
| Typical use | Nav 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 |
| Weakness | After flex-wrap, rows know nothing about each other, so nothing lines up | You 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”.