flex-direction: column 时 justify-content 控制垂直对齐,align-items 控制水平对齐;二者均依赖父容器在对应轴上有明确宽高,否则对齐失效。

flex-direction: column 时 justify-content 控制垂直排列
设 flex-direction: column 后,子项默认从上到下垂直堆叠,justify-content 就管纵向位置了。比如 justify-content: center 让整组子项在父容器高度内垂直居中,justify-content: space-between 则把首尾子项撑满上下边缘、中间等距分布。
常见错误是只写 flex-direction: column 却没配 justify-content,结果子项还是贴着顶部——因为默认值是 flex-start。
- 若要子项顶部对齐:用
justify-content: flex-start - 若要底部对齐:用
justify-content: flex-end - 若要均匀拉开间距:用
justify-content: space-around或space-evenly
align-items: center 实现子项水平居中
align-items 在 column 布局下控制的是**水平方向**(此时交叉轴是水平的),所以 align-items: center 才能让每个子项左右居中。它和 justify-content 是搭档,缺一不可。
容易踩的坑:
- 父容器宽度为
auto或被内容撑开,导致align-items: center没有参考宽度 → 检查开发者工具里 computedwidth是否 > 0 - 子项是内联元素(如纯文本)且没设
display: block或inline-block→ 文字会按基线对齐,看起来偏下 - 子项设置了
margin-left: auto或text-align: right→ 会覆盖align-items效果
父容器必须有可计算的宽高,否则对齐失效
justify-content 和 align-items 都依赖父容器在对应轴上有明确尺寸。垂直排列时,justify-content 需要父容器有高度(比如 height: 100vh 或 min-height: 500px),align-items 则需要父容器有宽度(比如 width: 100% 或固定值)。
典型失效场景:
- 父容器是
但没设html, body { height: 100%; } - 父容器套在
position: absolute的祖先里,却忘了给祖先设height - 父容器用了
display: inline-flex又没限制宽度 → 渲染宽度可能为 0
移动端尤其注意:100vh 在 Safari 地址栏收放时会跳变,可用 min-height: 100dvh 替代(Chrome 105+、Firefox 110+、Safari 16.4+ 支持)。
多行文字内容需额外加 text-align
如果子项是个 <div>,里面装了自动换行的多行文字,<code>align-items: center 只控制这个 <div> 自身的水平位置,不控制内部文字对齐。这时候得单独给子项加 <code>text-align: center。
别漏这两点:
- 子项要设
max-width(比如max-width: 80%),否则文字撑满全宽,text-align: center看不出效果 - 避免子项用
float或position: absolute—— 这些会让它脱离 flex 流,align-items完全不生效
真正卡住人的地方,往往不是属性写错,而是父容器的尺寸没被浏览器真正“看见”。调试时直接看 computed 样式里的 height 和 width 值,比猜更靠谱。











