问题:如何实现垂直居中?
垂直居中是 CSS 布局中最常见的需求之一,本文汇总多种实现方案。
核心方案
| 方法 | 适用场景 | 兼容性 |
|---|---|---|
| Flexbox | 现代浏览器 | IE11+ |
| Grid | 现代浏览器 | IE10+ |
| position + transform | 通用 | IE9+ |
| position + margin | 已知尺寸 | IE6+ |
| table | 兼容老浏览器 | IE6+ |
具体实现
1. Flexbox(推荐)
/* 水平垂直居中 */
.parent {
display: flex;
justify-content: center;
align-items: center;
}
/* 仅垂直居中 */
.parent {
display: flex;
align-items: center;
}优点:代码简洁,兼容性好
2. Grid
.parent {
display: grid;
place-items: center;
}优点:一行代码搞定
3. position + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}优点:无需知道父容器尺寸
4. position + margin(已知尺寸)
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin-left: -width/2;
margin-top: -height/2;
}缺点:需要已知子元素尺寸
5. table 兼容老浏览器
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}优点:兼容 IE6+
方案对比
| 方案 | 复杂度 | 兼容性 | 需知尺寸 |
|---|---|---|---|
| Flexbox | ⭐ | ⭐⭐⭐ | 否 |
| Grid | ⭐ | ⭐⭐⭐ | 否 |
| position+transform | ⭐⭐ | ⭐⭐⭐ | 否 |
| position+margin | ⭐⭐⭐ | ⭐⭐⭐⭐ | 是 |
| table | ⭐⭐ | ⭐⭐⭐⭐⭐ | 否 |
推荐
首选 Flexbox:
.parent {
display: flex;
justify-content: center;
align-items: center;
}次选 Grid:
.parent {
display: grid;
place-items: center;
}知识图谱
参考延伸
- CSS Tricks: Centering in CSS
- 垂直居中方法总结