最优解是 display: flex + justify-content: center + align-items: center,但父容器必须设显式高度;Grid 用 place-items: center 更简洁;绝对定位+transform 是不定宽高时的兜底方案。
直接用 display: flex + justify-content: center + align-items: center,95% 的场景下这就是最优解。别绕弯,别硬套老方案,除非你明确要兼容 IE9 或更低版本。
很多人写完发现没效果,根本原因是父容器没有显式高度。Flex 垂直居中依赖父容器的可用高度空间,height 为 auto 且子元素没撑开时,垂直方向就“没地方可居中”。
height(如 height: 300px 或 min-height: 100vh)width/height 为 auto、百分比、fit-content 都能正常居中body 或 html,记得先清除默认 margin,并设 height: 100% 或 100vh
display: -ms-flexbox,但现代项目基本可忽略当父容器本身已是 Grid 布局,或你想用更语义化的方式表达“整体居中”,place-items: center 比 Flex 更干净——它本质是 align-items: center 和 justify-items: center 的合并写法。
display: grid; place-items: center
grid-template-areas 或复杂轨道定义,place-items 可能被局部覆盖,优先检查计算后的 align-items
当你无法控制父容器样式(比如嵌入第三方 iframe)、或需要脱离文档流时,position: absolute + transform 是最可控的 fallback。
position: relative(或其它非 static 值)top: 50%; left: 50%; transform: translate(-50%, -50%)
transform 中的两个 -50% 含义不同:第一个是相对于自身宽度,第二个是相对于自身高度,这点极易混淆width/height 为 auto 也生效-webkit-transform 前缀(仅 iOS 7–9)很多“居中失效”不是技术问题,而是对 CSS 渲染机制理解偏差导致的。
text-align: center 只影响行内级内容,对块级子元素无效——除非你把它变成 inline-block
margin: 0 auto 只能水平居中,且要求块级元素有明确 width;垂直方向完全不起作用line-height 垂直居中只适用于单行文本,多行时会把行距撑开,视觉上反而偏下vertical-align: middle 不是对父容器居中,而是对“行框内其他 inline-level 元素”对齐,单独用必失败真正难的不是选哪种方案,而是看懂当前 DOM 结构和盒模型状态。打开浏览器 DevTools,盯住 computed 标签页里的 display、height、position 和 transform,比查十篇教程都管用。