标准答案
- 水平垂直居中要按场景选方案,没有唯一答案。
- 现代布局里最常用 Flex 和 Grid。Flex 用 display: flex、justify-content: center、align-items: center;Grid 用 display: grid、place-items: center。
- 只做块级元素水平居中,可以给固定宽度或 max-width 元素设置 margin: 0 auto。
- 单行文本垂直居中可以用 line-height 等于容器高度,但它不适合多行内容。
- 弹层或覆盖物居中常用 absolute 加 top: 50%、left: 50%、transform: translate(-50%, -50%)。总结就是:通用场景优先 Flex/Grid,特殊场景再选 absolute、line-height、margin auto。
题目解析
面试官问居中,通常不是想听十种写法,而是看你能不能按场景取舍。
Flex 和 Grid 的优点是无需知道子元素尺寸;absolute + transform 的优点是脱离文档流,适合弹层或覆盖物。
代码示例
现代页面最常用的居中方案是 Flex 或 Grid。
CSS
.by-flex {
display: flex;
align-items: center;
justify-content: center;
}
.by-grid {
display: grid;
place-items: center;
}
.by-position {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}常见误区
- 只背一种 absolute 居中,不会用 Flex/Grid。
- 用 line-height 做多行内容垂直居中,导致文本错位。
- 居中元素尺寸未知时还用负 margin。