place-items: center仅对Grid直接子元素生效,需父容器设display: grid且有高度;单元素居中用place-self: center;网格轨道居中用place-content: center。

直接用 place-items: center 就能同时搞定,但前提是父容器必须是 Grid 容器且有可用高度空间——否则它什么也不会做。
place-items: center 没反应?先查这三件事
这是最常卡住人的地方,浏览器不报错,但 computed styles 里看不到效果:
- 父元素是否真写了
display: grid或display: inline-grid?只写place-items: center而没设 display 类型,等于白写 - 父容器高度是否塌陷?比如没设
min-height: 100vh或height: 300px,而子元素又没撑高它,computed height 就是 0px - 目标子元素是不是被
Fragment、<div>包了一层?place-items只对**直接子元素**生效,隔一层就失效
单个子项居中别用 place-items,改用 place-self: center
想只让一个图标居中,其余文字左对齐?place-items: center 会把所有子项全拉到中心重叠,这不是你想要的:
- 给目标元素加
place-self: center,等价于justify-self: center+align-self: center - 它只影响当前元素,不影响兄弟节点
- 如果该元素用了
grid-row: 1 / 3跨两行,align-self: center会在这两行合并后的轨道内居中,不是整个容器高度 - 注意:目标元素必须是 Grid 容器的**直接子元素**,不能被 wrapper div 包裹
网格整体居中(比如一个 3×3 图标块)要用 place-content: center
当你要居中的不是“单个元素”,而是“整套网格轨道”(比如定义了 grid-template-columns: repeat(3, 100px) 的一块区域),那就该换属性了:
立即学习“前端免费学习笔记(深入)”;
-
place-content: center是justify-content: center和align-content: center的简写 - 它控制的是**网格轨道在容器内的位置**,不是子项在单元格里的位置
- 生效前提:容器尺寸 > 网格轨道总尺寸(比如容器宽 500px,但列总宽才 300px,才有“多余空间”可居中)
- 别和
place-items混着用——作用对象完全不同,混用反而会让布局不可预测
真正容易被忽略的点是:Grid 居中依赖轨道尺寸。没有显式行列定义(grid-template-rows)、又没内容撑开高度时,align-self 或 place-items 都找不到对齐基准。这时候加一行 min-height: 100vh 或 grid-template-rows: 1fr,比反复调 justify-content 有用得多。


















