place-items: center 能实现横竖居中,但要求容器有明确宽高;常见失效原因是容器未撑开、父容器限制尺寸或误用 inline-grid、place-content 等。
place-items: center 能直接实现横竖居中,但前提是容器有明确高度和宽度空间——它不是“魔法”,而是依赖网格轨道的可用区域。
place-items: center 没反应?最常见原因是容器本身没撑开:没有显式宽高、父容器限制了尺寸、或用了 inline-grid。
computed height 和 computed width,是否为 0px 或远小于预期place-content: center——后者对齐的是轨道块(rows/columns),不是子元素flex,且设了 align-items: flex-start,会覆盖 Grid 容器的垂直空间分配background: #f0f 到容器上,看色块是否铺满你认为“该有”的区域单靠 place-items: center 不足以触发垂直居中;交叉轴(默认为 y 轴)需要可参考的长度。
min-height: 100vh 比 height: 100vh 更安全,避免移动端键盘弹出时视口高度突变height 或 min-height,且未被 overflow: hidden 或 flex: 0 0 auto 截断height: auto —— 这会让容器塌陷,align-items 失去作用基准html, body { height: 100%; margin: 0; }
place-items 是容器级属性,会影响所有直接子项。多个子元素一起被拉到中心,结果就是重叠。
立即学习“前端免费学习笔记(深入)”;
place-self: center 写在目标子元素上,精准控制单个项justify-self: center; align-self: center;,调试时更易分离问题flex 或 grid 容器,place-self 只影响它在父网格单元里的位置,不影响其内部布局grid-template-rows),垂直方向可能仍不生效——此时加 min-height 或 height 到父容器真正卡住人的,从来不是 place-items: center 写错,而是忘了它背后那两个沉默的前提:容器得有宽,也得有高。