Flexbox 与 Grid 速查表
Flexbox 沿一个轴排列项目,Grid 在二维平面里摆放。同一套盒模型,不同的能力。
Flexbox — 容器属性
| 属性 | 常用值 | 作用 |
|---|---|---|
| display | flex | Enables flex layout |
| flex-direction | row · column · row-reverse | Main axis direction |
| justify-content | flex-start · center · space-between · space-around | Distribution along the main axis |
| align-items | stretch · center · flex-start · flex-end | Alignment on the cross axis |
| flex-wrap | nowrap · wrap | Whether items can line-break |
| gap | 12px · 8px 16px | Spacing between items (row column) |
Flexbox — 项目属性
| 属性 | 常用值 | 作用 |
|---|---|---|
| flex-grow | 0 · 1 · 2 | How much free space an item absorbs |
| flex-shrink | 1 · 0 | How willingly an item shrinks |
| flex-basis | auto · 200px · 0 | Initial size before growing/shrinking |
| flex | 1 · 0 auto · 1 1 0 | Shorthand for grow shrink basis |
| align-self | auto · center · flex-end | Per-item cross-axis override |
| order | 0 · 1 · -1 | Visual reordering without touching HTML |
Grid — 容器属性
| 属性 | 常用值 | 作用 |
|---|---|---|
| display | grid | Enables grid layout |
| grid-template-columns | repeat(3, 1fr) · 200px 1fr · auto-fill minmax(240px, 1fr) | Defines the columns |
| grid-template-rows | auto · repeat(2, minmax(0, 1fr)) | Defines the rows |
| gap | 16px · 8px 24px | Gutters between tracks |
| justify-items / align-items | start · center · stretch | Placement inside each cell |
| place-items | center | Shorthand for align + justify items |
常见问题
Flexbox or Grid — how do I choose?
One-dimensional (a toolbar, a nav, a card row that should stretch) → Flexbox. Two-dimensional or explicit rows AND columns → Grid. Most real layouts use both.
Why do my grid images overflow?
Grid tracks default to auto, so wide content expands the track. Use minmax(0, 1fr) instead of 1fr to force tracks to shrink below content size.
justify-content vs align-items?
justify = main axis, align = cross axis — and the main axis is whichever direction flex-direction points. Flip the direction and the two swap roles.