一、容器属性(display: flex 的那一层)
加在父元素上
| 属性 | 默认值 | 可取值 | 一句话说明 |
|---|---|---|---|
| flex-direction | row | row / row-reverse / column / column-reverse | 决定主轴方向:横着排还是竖着排。 |
| flex-wrap | nowrap | nowrap / wrap / wrap-reverse | 项目超宽时是否折行。 |
| flex-flow | row nowrap | 上面两个的缩写,先方向后折行 | 例:flex-flow: column wrap; |
| justify-content | flex-start | flex-start / flex-end / center / space-between / space-around / space-evenly | 主轴上「整行」怎么对齐。 |
| align-items | stretch | stretch / flex-start / flex-end / center / baseline | 交叉轴上「单行」里每个项目怎么对齐。 |
| align-content | stretch | stretch / flex-start / flex-end / center / space-between / space-around / space-evenly | 交叉轴上「多行」之间怎么分布;只有 wrap 出多行时才生效。 |
| gap | 0 | 长度或百分比 | 行列之间的固定缝隙,不用再加 margin。 |
二、项目属性(flex 子元素)
加在子元素上
| 属性 | 默认值 | 可取值 | 一句话说明 |
|---|---|---|---|
| flex-grow | 0 | 数字 ≥ 0 | 剩余空间要不要「瓜分」;0 表示不抢,1 表示抢 1 份。 |
| flex-shrink | 1 | 数字 ≥ 0 | 空间不够时能不能「被压缩」;0 表示不压缩,1 表示可压缩。 |
| flex-basis | auto | 长度或百分比 | 项目「初始主尺寸」,优先级高于 width/height。 |
| flex | 0 1 auto | 上面三个的缩写,顺序固定 grow shrink basis | 常见写法:flex: 1; 等价 1 1 0%;flex: none; 等价 0 0 auto。 |
| align-self | auto | auto / 其余同 align-items | 单项目覆盖父级的 align-items。 |
| order | 0 | 整数 | 数字越小越靠前,可负数,不改变 DOM 顺序,只改变视觉顺序。 |
三、5 条万能公式
水平居中
javascript
.box { display: flex; justify-content: center; }
垂直居中
javascript
.box { display: flex; align-items: center; }
完全居中
javascript
.box { display: flex; justify-content: center; align-items: center; }
右侧固定、左侧自适应
javascript
.left { flex: 1; } /* 抢剩余空间 */
.right { flex: 0 0 200px; } /* 不抢也不缩,固定 200px */
多列等高 + 自动折行
javascript
.container {
display: flex;
flex-wrap: wrap;
align-items: stretch; /* 默认就是 stretch,可省略 */
}
.item {
flex: 1 1 300px; /* 最小 300px,空间够就等分,不够就折行 */
}
四、容易踩的 4 个小坑
-
align-content只有多行才生效,单行时再怎么改都看不出效果。 -
flex-basis优先级高于width/height;如果想用 width,就把 basis 设成 auto 或 0。 -
项目内文本
white-space: nowrap会让项目「撑开」导致溢出,记得给项目加min-width: 0或overflow:hidden。 -
order只能改视觉顺序,屏幕阅读器仍按 DOM 顺序朗读,别用它做语义重排。