一、已知宽高元素的水平垂直居中
方法 1:绝对定位 + margin 负值(老方法)
.parent {
position: relative;
}
.child {
width: 200px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px; /* 宽度一半 */
margin-top: -50px; /* 高度一半 */
}
原理:
先移动到父元素中心
再往回拉自己的一半
⚠️ 缺点:必须知道宽高。
二、未知宽高元素居中(常考)
方法 2:absolute + transform(经典推荐)
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
原理:
left/top: 50% → 移动到父元素中心
translate(-50%, -50%) → 再移动自身一半
✅ 不需要知道宽高
✅ 兼容性好
✅ 面试常用答案
三、Flex 布局(现代主流 ⭐⭐⭐)
方法 3:flex 居中(最推荐)
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
原理:
主轴用 justify-content
交叉轴用 align-items
✅ 代码最简单
✅ 真实项目最常用
✅ React / Vue 项目里最常见
四、Grid 布局(更简单)
方法 4:grid 居中
.parent {
display: grid;
place-items: center;
}
等价于:
justify-items: center;
align-items: center;
✅ 一行搞定
✅ 现代浏览器支持良好
五、行内元素居中
1️⃣ 水平居中
.parent {
text-align: center;
}
2️⃣ 单行文本垂直居中
.parent {
height: 100px;
line-height: 100px;
}
⚠️ 只适合单行文本。
六、利用 table 布局(了解即可)
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}
老项目中可能会看到。
七、完整对比总结(面试直接说)
| 方法 | 是否需要固定宽高 | 是否推荐 |
|---|---|---|
| margin 负值 | ✅ 需要 | ❌ |
| absolute + transform | ❌ | ✅ |
| flex | ❌ | ⭐⭐⭐ 推荐 |
| grid | ❌ | ⭐⭐ |
| line-height | 只限单行 | 特殊场景 |
八、面试标准回答模板
如果面试官问你,你可以这样回答:
CSS 实现水平垂直居中常见有三种方式:
- 绝对定位 + transform
- Flex 布局(主流推荐)
- Grid 布局
在实际项目中一般使用 flex,因为代码简洁且适配性好。
九、结合你实际项目场景(比如你做 Ant Design 后台)
例如弹窗 loading 居中:
.loading {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}