在CSS布局中,元素水平垂直居中是高频需求。根据父容器和子元素是否确定尺寸、是否需要兼容旧浏览器,可以选择不同方案。下面介绍几种实用且稳定的实现方式。

一、使用Flexbox实现居中
Flexbox是现代布局首选,只需在父容器设置相关属性,子元素会自动居中,不需要知道子元素宽高。
/* 父容器 */
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 300px;
}
/* 子元素 */
.child {
width: 100px;
height: 100px;
background: #409eff;
}
二、绝对定位加transform
当子元素尺寸未知时,可以用绝对定位将左上角移到中心,再用transform回退自身一半。
.parent {
position: relative;
height: 300px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #67c23a;
}
三、Grid布局方式
CSS Grid也能一行属性完成居中,语法非常简洁。
.parent {
display: grid;
place-items: center;
height: 300px;
}
四、表格单元格方式
将父级转为表格单元格,利用vertical-align和margin实现兼容旧浏览器的居中。
.parent {
display: table-cell;
width: 300px;
height: 300px;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
}
方法对比
| 方法 | 是否需要知尺寸 | 兼容性 |
|---|---|---|
| Flexbox | 否 | 现代浏览器 |
| 绝对定位+transform | 否 | IE9+ |
| Grid | 否 | 较新浏览器 |
| table-cell | 否 | 全部浏览器 |
实际项目中,推荐优先使用flexbox或grid,代码清晰且维护成本低。若需兼容非常旧的環境,再考虑table-cell方案。