新手用Flex布局最常踩的坑是混淆主轴与交叉轴:主轴由flex-direction决定(row为水平,column为垂直),justify-content控制主轴对齐,align-items控制交叉轴对齐;二者作用方向随flex-direction动态变化,且align-items需父容器有明确交叉轴尺寸才生效。
新手用 Flex 布局时,最常踩的坑就是搞混主轴(main axis)和交叉轴(cross axis),导致 justify-content 和 align-items 效果“不按预期”出现——其实不是 CSS 有问题,是方向理解错了。
很多人默认主轴是水平向右,所以看到 justify-content: center 没居中就慌了。但只要写了 flex-direction: column,主轴立刻变成垂直向下,此时 justify-content 控制的就是**垂直方向**的对齐,而 align-items 才管水平对齐。
flex-direction: row(默认)→ 主轴水平 → justify-content 水平生效,align-items 垂直生效flex-direction: column → 主轴垂直 → justify-content 垂直生效,align-items 水平生效flex-direction: row-reverse 或 column-reverse 会翻转主轴起点,影响 justify-content 的“左/上”参照基准新手常给某个子元素单独加 align-self 却忘了父容器没设 align-items,或误以为 align-items 能让某一个孩子“自己居中”。实际上:
align-items 是父容器属性,定义所有子项在交叉轴上的默认对齐方式align-self(如 align-self: flex-start),但它仍受父容器交叉轴范围限制height: auto),且子项没撑开容器,交叉轴可能“没空间”,align-items 就看起来“失效”这是高频混淆点:justify-content 只管主轴,永远不管交叉轴。哪怕你写 justify-content: center 并希望内容在盒子中间,若主轴是水平的,它只左右居中;上下居中得靠 align-items: center(前提是父容器有明确的交叉轴尺寸)。
display: flex; justify-content: center; align-items: center;
align-items: center 仍会让子项在“视觉上偏上”——因为交叉轴长度=子项高度,没多余空间可居中min-height: 100vh 或明确 height,再配合 align-items: center
当子项太多换行(flex-wrap: wrap),主轴方向不变,但交叉轴会从“单行”变成“多行堆叠方向”。这时:
justify-content 依然只控制**每行内部**主轴对齐(如每行内左对齐)align-content 才控制**行与行之间**在交叉轴上的分布(比如多行上下间距、整体居中)align-items 仍然控制**每一行内各子项**在交叉轴上的对齐(比如每行的子项都顶部对齐)