grid容器需设明确高度(如min-height:100vh)才能使align-items生效;align-items控制垂直居中,水平居中需justify-content;单元素居中用二者组合,多元素同理;grid适合二维布局扩展,flex更轻量但层级敏感。
很多人写完 display: grid 和 align-items: center 发现元素没居中,根本原因是父容器没设置高度。CSS Grid 的 align-items 是沿行轴(block axis)对齐,它依赖容器的可用块方向空间——如果容器高度由内容撑开(即 height: auto),那“居中”就失去参照基准。
height: 100vh、min-height: 100vh 或具体像素值min-height: 100vh,避免内容超长时被截断align-items,还需配合 justify-items: center(或 justify-content)实现水平居中align-items 控制的是**所有网格项在行轴(垂直方向)上的对齐方式**,而水平居中得看列轴——这时该用 justify-content(作用于整个网格轨道)或 justify-items(作用于单个网格项)。
align-items: center + justif
y-content: center
align-items + justify-content,它们会统一作用于所有项grid-template-rows 或 grid-template-columns,align-items 仍有效,但 justify-content 只在轨道总宽小于容器时才触发对齐div.container {
display: grid;
min-height: 100vh;
align-items: center;
justify-content: center;
}
单纯居中一个元素,display: flex 确实更轻量。但 grid 的优势在于:它天然支持二维布局,且居中逻辑不依赖子元素是否为直接子节点(flex 对嵌套层级敏感)。当你后续要扩展成多行多列、响应式栅格、或需要 grid-area 精确控制位置时,一开始就用 grid 能避免重构。
place-items: center 作为兼容写法place-items: center 是 align-items 和 justify-items 的简写,不是 justify-content 的别名,别误用有人会给 grid 子项加 margin: auto 试图居中,这在 grid 中虽能工作,但属于“副作用”,且行为不稳定——尤其当子项设置了 grid-column 或 grid-row 后,margin: auto 可能被忽略或引发意外间隙。
align-items / justify-content),语义清晰、可控性强margin 配合 place-self
align-items 是否被父级或继承值覆盖