水平居中
1. 行内/行内块元素
.parent {
text-align: center;
}
2. 单个块级元素(固定宽度)
.element {
width: 300px;
margin: 0 auto;
}
3. Flexbox
.parent {
display: flex;
justify-content: center;
}
4. Grid
.parent {
display: grid;
justify-content: center;
}
5. 绝对定位(已知宽度)
.element {
position: absolute;
left: 50%;
width: 300px;
margin-left: -150px; /* 负值宽度的一半 */
}
6. 绝对定位(未知宽度)
.element {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
垂直居中
1. 单行文本/行内元素
.parent {
height: 200px;
line-height: 200px; /* 等于容器高度 */
}
2. Flexbox
.parent {
display: flex;
align-items: center;
}
3. Grid
.parent {
display: grid;
align-items: center;
}
4. 绝对定位(已知高度)
.element {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* 负值高度的一半 */
}
5. 绝对定位(未知高度)
.element {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
6. 表格布局
.parent {
display: table-cell;
vertical-align: middle;
}
水平垂直居中
1. Flexbox(最推荐)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
/* 替代写法 */
.parent {
display: flex;
}
.child {
margin: auto;
}
2. Grid(现代浏览器)
.parent {
display: grid;
place-items: center;
}
/* 替代写法 */
.parent {
display: grid;
}
.child {
margin: auto;
}
3. 绝对定位 + transform(未知尺寸)
.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4. 绝对定位 + 负边距(已知尺寸)
.element {
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 200px;
margin-top: -100px; /* 高度一半 */
margin-left: -150px; /* 宽度一半 */
}
5. 表格布局
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}
实用技巧与注意事项
1. 居中最佳实践对比表
方案 | 优点 | 缺点 | 兼容性 |
---|---|---|---|
Flexbox | 简洁、灵活、响应式 | 旧浏览器支持有限 | IE10+ |
Grid | 最简洁写法 | 旧浏览器支持不足 | IE部分支持 |
绝对定位+transform | 未知尺寸完美居中 | 脱离文档流 | IE9+ |
负边距 | 可靠定位 | 需知道元素尺寸 | 所有浏览器 |
表格布局 | 兼容性最好 | 语义不准确 | 所有浏览器 |
2. 解决常见问题
垂直居中文本换行问题:
.parent {
display: table-cell;
vertical-align: middle;
}
/* 替代方案 */
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
多行文本垂直居中:
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
3. 响应式居中技巧
根据屏幕大小调整居中方式:
.container {
display: flex;
justify-content: center;
}
@media (max-width: 768px) {
.container {
flex-direction: column;
align-items: center;
}
}
动态居中元素:
.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 响应式限制大小 */
max-width: 90%;
max-height: 90%;
}
4. 特殊场景解决方案
固定在视口中心:
.element {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1000;
}
网格系统中的居中:
<div class="row">
<div class="col-md-6 offset-md-3">
<!-- 宽度50%并居中 -->
</div>
</div>
Flexbox嵌套居中:
<div class="d-flex justify-content-center align-items-center" style="height: 100vh;">
<div>
<h2>双重保护确保居中</h2>
<div class="d-flex justify-content-center">
<button>居中按钮</button>
</div>
</div>
</div>
总结
- 现代项目首选Flexbox/Grid:简洁高效,代码量少
- 兼容旧浏览器:表格布局或负边距方案
- 未知尺寸元素居中:transform是最佳选择
- 响应式设计:结合媒体查询调整居中策略
- 混合使用:根据实际场景组合不同技术