使用css Grid实现居中可通过place-items、justify-items与align-items或place-self完成。1. place-items: center最简洁,适用于所有子元素;2. 分开设置justify-items和align-items可精细控制;3. place-self: center用于单独居中某个子项。需确保容器有高度且启用display: grid,适合响应式设计。

用 CSS Grid 实现水平和垂直居中非常简单,只需要在容器上启用 Grid 布局,并设置对齐方式即可。核心是利用 place-items 或分别使用 justify-items 与 align-items。
方法一:使用 place-items
这是最简洁的方式,适用于整个网格容器内的所有子元素都需要居中的场景。
place-items: center; 可以同时设置水平和垂直居中。
.container { display: grid; place-items: center; height: 100vh; /* 确保容器有高度 */ } .item { /* 子元素内容会自动居中 */ }
html 示例:
<div class="container"> <div class="item">居中内容</div> </div>
方法二:分别设置 justify-items 和 align-items
如果你需要更细粒度的控制,可以分开写两个属性。
- justify-items: center; 控制横向(行轴)对齐
- align-items: center; 控制纵向(列轴)对齐
CSS 示例:
立即学习“前端免费学习笔记(深入)”;
.container { display: grid; justify-items: center; align-items: center; height: 100vh; }
方法三:只让某个子项居中(使用 place-self)
如果只想让特定子元素居中,可以在子元素上使用 place-self。
例如:
.container { display: grid; height: 100vh; } .item { place-self: center; }
这种方式不会影响其他子元素的布局。
补充说明
Grid 的居中方式不依赖内容大小,也不需要知道元素尺寸,非常适合响应式设计。
- 确保父容器有明确的高度(如 100vh、固定值或 flex 嵌套)
- display: grid 是前提
- place-items 是 justify-items + align-items 的简写
基本上就这些,不复杂但容易忽略容器高度的问题。
暂无评论


