使用 place-items: center; 可简洁实现所有子元素水平垂直居中;2. 通过 justify-content 和 align-items 分别控制主轴与交叉轴居中;3. 对单个子元素使用 justify-self 和 align-self 实现独立居中,灵活适配不同需求。

在 CSS Grid 布局中,让子元素在父容器内水平垂直居中非常简单。只需要在父元素上设置 Grid 相关属性,即可轻松实现居中对齐。
1. 使用 place-items 居中
这是最简洁的方法,适用于希望所有子元素都居中的场景。
place-items: center; 可以同时设置水平和垂直方向的对齐方式。示例代码:
.container {
display: grid;
place-items: center;
height: 100vh; /* 示例高度 */
}
.item {
/* 子元素无需额外样式 */
}
2. 分别设置 justify-content 和 align-items
如果需要更精细控制,可以分别设置主轴和交叉轴的对齐方式。
- justify-content: center; 控制子元素在行上的水平居中
- align-items: center; 控制子元素在列上的垂直居中
示例代码:
.container {
display: grid;
justify-content: center;
align-items: center;
height: 100vh;
}
3. 对单个子元素使用 justify-self 和 align-self
当只希望某个特定子元素居中时,可以在该子元素上单独设置。
立即学习“前端免费学习笔记(深入)”;
- justify-self: center; 让该元素在网格单元格中水平居中
- align-self: center; 垂直居中
示例代码:
.container {
display: grid;
height: 100vh;
}
.item {
justify-self: center;
align-self: center;
}
基本上就这些方法,根据实际需求选择整体居中还是个别控制,Grid 提供了灵活又直观的对齐能力。










