日常开发的时候会碰到很多需要居中元素的场景,尤其对于强迫症来说,为了一点点偏差疯狂手调margin(比如我自己),这篇专门讲一下CSS中实现元素水平垂直居中的方法。
直接先上总结:
- Flex布局:父元素设置
display: flex
,justify-content: center
,align-items: center
- Grid布局:父元素设置
display: grid
,place-items: center
- 设置绝对定位
position: absolute
,top: 50%
,left: 50%
,transform: translate(-50%, -50%)
- 设置绝对定位
position: absolute
,上下左右值设为0,margin: auto
- (单行文本)设置行高和
text-align: center
- (仅实现水平居中 )(多个内联元素/设置了
display: inline-block
的块级元素)设置 text-align: center
想看详细介绍的继续往下看:
一、Flex布局(最常用)
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
height: 500px; /* 需要定义容器高度 */
}
二、Grid布局(最高效)
.parent {
display: grid;
place-items: center; /* 同时实现水平垂直居中 */
height: 500px;
}
三、绝对定位 + transform
.parent {
position: relative; /* 父元素需要有定位 */
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
四、绝对定位 + margin:auto
(已知尺寸)
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 200px; /* 必须指定宽高 */
height: 100px;
}
五、行高 + text-align: center
(单行文本)
.parent {
height: 200px;
line-height: 200px; /* 垂直居中 */
text-align: center; /* 水平居中 */
}