
本文详解 justify-content 与 align-items 在 Flex 布局中的协同作用,纠正 justify-items 的误用,并通过代码示例说明如何在 flex-direction: column 下同时实现内容的水平与垂直居中。
本文详解 `justify-content` 与 `align-items` 在 flex 布局中的协同作用,纠正 `justify-items` 的误用,并通过代码示例说明如何在 `flex-direction: column` 下同时实现内容的水平与垂直居中。
在使用 Flexbox 进行布局时,一个常见误区是混淆 justify-items 和 justify-content。实际上,justify-items 并不适用于 Flex 容器——它是 CSS Grid 中的属性;而 Flex 布局中控制主轴对齐的正确属性是 justify-content,控制交叉轴对齐的是 align-items。
在你的代码中:
section {
display: flex;
flex-direction: column;
justify-items: center; /* ❌ 错误:该属性对 Flex 无效 */
align-items: center; /* ✅ 正确:在 column 下控制水平居中(交叉轴) */
justify-content: center; /* ✅ 补充:在 column 下控制垂直居中(主轴) */
}
由于设置了 flex-direction: column,此时:
-
主轴为垂直方向 →
justify-content: center控制子元素在垂直方向上的居中; -
交叉轴为水平方向 →
align-items: center控制子元素在水平方向上的居中。
此外,原始代码中将 h1 和 form 设置为 width: 50px; height: 50px,导致内容(如文字“Lista Tarefas”和表单控件)严重溢出,视觉上无法体现居中效果。建议使用合理尺寸并配合 text-align: center 保证内部文本/按钮对齐:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-size: 62.5%;
height: 100%;
}
body {
font: 1.6rem Arial, sans-serif;
height: 100%;
}
#root {
height: 100%;
}
h1,
form {
width: 200px;
height: 50px;
text-align: center; /* 确保内部文本与按钮居中 */
}
section {
max-width: 50%;
height: 100%;
display: flex;
flex-direction: column;
background-color: #ccc;
justify-content: center; /* ✅ 垂直居中(主轴) */
align-items: center; /* ✅ 水平居中(交叉轴) */
}
HTML 结构保持不变:
<div id="root">
<section><h1>Lista Tarefas</h1>
<form>
<input type="text" placeholder="Tarefa..."><button type="submit">Enviar</button>
</form>
</section>
</div>
✅ 关键要点总结:
- Flex 容器中不存在
justify-items,务必使用justify-content控制主轴对齐; -
flex-direction决定主轴方向,进而影响justify-content和align-items的作用轴; - 子元素尺寸需合理,避免内容溢出掩盖布局效果;
- 若需进一步微调单个子项位置,可结合
margin: auto或align-self/justify-self(后者仅在 Grid 中有效)。
掌握这一组合,即可稳定、可靠地实现任意方向的双轴居中。










