Flex 只有两个轴:跟随 flex-direction 旋转的主轴,与它垂直的交叉轴

属性名分两套:justify-content 永远管主轴,align-* 永远管交叉轴。direction 从 row 改成 column,两者的表现会跟着互换 —— 这是 Flex 最大的困惑来源,用图记住而不是背。

① flex-direction:排队的方向

row(默认)
1
2
row-reverse:DOM 顺序不变,视觉反向
1
2
column:主轴变成垂直
justify 现在管上下
align 管左右

row-reverse 会同时反转视觉阅读顺序,对读屏器和 Tab 顺序没有影响,可能造成「看到的顺序与听到的顺序不一致」,慎用。

② justify-content:主轴上怎么分配剩余空间

flex-start
1
center
1
flex-end
1
space-between:两端贴边,空隙均分
A
B
space-around:每个元素左右各留一份
A
B
space-evenly:所有空隙严格相等
A
B

只有当容器有剩余空间时它们才有区别;子项已经铺满时全都长一样。

③ align-items:交叉轴上怎么站

stretch(默认,需子项不设高度)
固定高
flex-start
顶对齐
center
垂直居中一行代码
flex-end
底对齐
baseline:按文字基线对齐,字号不同时更整齐
大字号

④ align-self:单个子项叛逆

center
align-self: flex-end
align-self: stretch

⑤ gap:容器间距的正确写法

gap: 8px
A
B
C
gap: 24px
A
B
.list { display: flex; gap: 12px 20px; }   /* 行间距 列间距;也可写 gap: 12px 同时生效 */
/* gap 只加在「相邻之间」,不会给首尾多出空白 —— 从此不需要 :last-child { margin-right: 0 } */
/* gap 同样适用于 grid 与多列 flex-wrap(换行时行间距也归它管) */

最小可用配方

/* 水平居中 */      .c { display: flex; justify-content: center; }
/* 垂直居中 */      .c { display: flex; align-items: center; }
/* 完全居中 */      .c { display: flex; align-items: center; justify-content: center; }
/* 完全居中(grid 一行搞定) */ .c { display: grid; place-items: center; }
/* 左右两端 */      .bar { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
/* 一列纵向 */      .col { display: flex; flex-direction: column; gap: 8px; }