通过 align-items 和 justify-items 可实现网格项在单元格内的居中对齐:align-items: center 实现垂直居中,justify-items: center 实现水平居中,二者结合可使元素完全居中,且作用于所有子项,单独控制则可用 align-self 或 justify-self 覆盖。

在使用 CSS Grid 布局时,让网格内的元素居中对齐是一个常见需求。可以通过 align-items 和 justify-items 两个属性分别控制交叉轴和主轴方向上的对齐方式。
align-items: center — 垂直居中(沿行轴方向)
这个属性作用于网格容器,用于设置所有网格项在列轴(block axis),也就是垂直方向上的对齐方式。
当设置为 center 时,每个网格项会在其所在的网格区域中垂直居中。示例:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
align-items: center; /* 垂直居中 */
height: 400px;
}
此时,无论网格项内容多少,它们都会在单元格的上下方向居中显示。justify-items: center — 水平居中(沿列轴方向)
该属性控制网格项在行轴(inline axis),即水平方向上的对齐。
立即学习“前端免费学习笔记(深入)”;
示例:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
justify-items: center; /* 水平居中 */
}
这样每个格子中的内容会相对于列宽在中间位置对齐。同时居中:align-items 与 justify-items 结合使用
若希望网格项在其单元格内完全居中(即水平垂直都居中),可以同时设置两个属性:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
align-items: center;
justify-items: center;
height: 100vh;
}
这时每个网格项的内容会在各自的格子中居于正中心。注意:align-items 和 justify-items 是作用于所有网格项的统一对齐方式。如果需要单独控制某个网格项,可使用 align-self 或 justify-self 在具体项目上覆盖。
基本上就这些。合理使用这两个属性,可以让 Grid 布局中的内容对齐更直观、简洁。









