实现元素水平垂直居中的方式有哪些?
1. 行内元素:text-align + line-height
.parent { text-align: center; line-height: 300px; }
.child { display: inline-block; }
2. 块级元素:绝对定位 + 负 margin(已知子元素宽高)
.parent { position: relative; }
.child {
position: absolute;
left: 50%; top: 50%;
margin-left: -100px; /* 子元素宽的一半 */
margin-top: -50px; /* 子元素高的一半 */
}
3. 绝对定位 + transform(未知子元素宽高)
.parent { position: relative; }
.child {
position: absolute;
left: 50%; top: 50%;
transform: translate(-50%, -50%);
}
4. 绝对定位 + margin: auto(已知子元素宽高)
.parent { position: relative; }
.child {
position: absolute;
left: 0; top: 0; right: 0; bottom: 0;
margin: auto;
width: 200px; height: 100px;
}
5. flex 弹性盒(推荐)
.parent {
display: flex;
justify-content: center; /* 主轴 */
align-items: center; /* 交叉轴 */
}
6. grid 网格布局
.parent {
display: grid;
place-items: center;
}
补充:实际项目中 优先推荐 flex / grid,写法简洁且对子元素尺寸无要求;绝对定位 + transform 适合需要脱离文档流的弹窗/浮层;负 margin 法已较少使用。



