place-items: center 是最简居中方案,但需父容器有高度(如 min-height: 100vh),否则塌陷失效;兼容现代浏览器,IE 不支持;单元素居中用 place-self: center;可拆分为 justify-items 和 align-items 便于调试;Grid 与 Flex 的 align-items 作用域不同,勿混用 display。
直接写 place-items: center 就能同时搞定水平和垂直居中,前提是父容器得“撑开”——比如设 height: 100vh、min-height: 100vh,或嵌套在 flex 容器里。否则 Grid 容器高度塌陷,子元素看似没动,其实是被挤在顶部了。
display: grid; place-items: center;,但父容器没设高,结果完全不居中.container {
display: grid;
place-items: center;
min-height: 100vh;
}place-items 是作用于整个容器的,所有子项都会被居中;而 place-self: center 只影响单个元素,其他子项照常按默认网格流排列——这点在卡片列表、弹窗、通知气泡等场景特别实用。
display: grid,但不用设 place-items
.container { display: grid; }
.main-item { place-self: center; }place-items: center 是简写,等价于 justify-items: center; align-items: center;。分开写的好处是:可以单独调整某一个方向,比如只水平居中(justify-items: center)、或只垂直居中(align-items: center),也方便后续加响应式断点。
justify-items 和 align-items 是否被其他规则覆盖(比如全局重置样式)align-items 控制的是“行内所有网格项在其单元格中的垂直对齐”,不是整个容器内容的垂直位置——所以它依赖网格轨道定义(哪怕隐式)align-items 和 justify-items 效果和 place-items 一致;但若有多行多列,它们只影响每个单元格内的对齐,而非整体居中虽然 Grid 居中更“二维”,但如果你的布局本质是一维(比如仅需上下左右居中一

align-items 在 Flex 中控制交叉轴(垂直方向),在 Grid 中控制行内对齐——概念相同,但作用域不同display: grid 和 display: flex,后者会覆盖前者