text-align: center 仅对行内内容生效,对块级元素自身无效;块级元素水平居中需用 margin: 0 auto(须设宽度)或 flex justify-content;垂直居中单行用 line-height,多行用 flex align-items;绝对定位居中需配合 transform。
当 text-align: center 看起来“没反应”,大概率不是写错了,而是元素本身不满足触发条件。它只对**行内内容**(如文字、inline 元素)生效,对块级容器自身的定位无影响。
display: inline-block 或未设宽度,导致实际可渲染宽度远小于视口,文字在“窄盒子”里已居中,但视觉上像没动display: block(比如 div、p),此时 text-align 对它内部文字有效,但对它自身位置无效——想移动这个块,得用别的方法float 或 position: absolute,脱离了文档流,text-align 失去作用对象margin: 0 auto 是最常用方案,但它有硬性前提:元素必须是块级(display: block 或 inline-block),且**宽度不能是 auto**(即必须显式设置 width、max-width 或 fit-content)。
.box {
width: 300px; /* 必须指定宽度 */
margin: 0 auto; /* 左右外边距自动均分 */
}width: 100%,margin: 0 auto 无效(左右没剩余空间可分)justify-content: center,更可靠且无需设宽left: 50%; transform: translateX(-50%) 模拟居中,兼
单行文字垂直居中,line-height 最简单;多行或需响应式,则必须用 flex 或 grid。
line-height 只适用于单行,且值需等于容器高度(如 height: 40px; line-height: 40px),换行会彻底错乱display: flex; align-items: center 对单行/多行都稳定,但老版本 Safari 对 flex 的 align-items 支持有 bugvertical-align: middle 配合 display: table-cell,语义混乱、调试困难,现代项目基本淘汰用 position: absolute 定位元素时,居中常写成 top: 50%; left: 50%,但这会让元素左上角落在中心点,文字看起来偏右下。
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 必须补上这句 */
}transform 是高频错误,尤其当元素宽高不固定时,margin 无法动态计算transform 触发硬件加速,性能比纯 top/left 更好,但可能影响 z-index 层叠上下文position: relative,absolute 元素会相对于最近定位祖先或初始包含块定位,容易“飞走”实际项目中最容易被忽略的是盒模型本身的尺寸行为:padding、border 是否计入 width,box-sizing 是否统一为 border-box。一个看似简单的居中,往往卡在这些隐性约束上。