前言
初级前端面试必考题,很多面试官都喜欢问这个问题。实习生的我面试遇到好几次了,在这里做一下总结。
水平垂直居中元素宽高固定
1.absolute + 负margin
2.absolute + margin auto
3.absolute + calc
水平垂直居中元素宽高不固定
1. absolute + transform
2. text-align + lineheight + vertical-align
3. css-table
4. flex
5. grid
公共Html代码
<div class="parent">
<div class="child"></div>
</div>
公共Css样式
.parent{
border: 1px solid cadetblue;
width:300px;
height:300px;
}
.child{
height: 100px;
width: 100px;
background: cornflowerblue;
}
1.absolute + 负margin
.child{
height: 100px;
width: 100px;
background: cornflowerblue;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
绝对定位的百分比是相对于父元素的宽高,top:50% left:50%是基于子元素的左上角偏移的,效果如下图:

在使用子元素的外边距为子元素宽高一半的负值进行相反方向偏移就可以让子元素居中了。
2.absolute + margin auto
.child{
height: 100px;
width: 100px;
background: cornflowerblue;
position: absolute;
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
设置各个方向的距离都是0,margin设为auto代表子元素到父元素上下、左右的距离相同,就可以实现水平垂直居中了。
3.absolute + calc
.child{
height: 100px;
width: 100px;
background: cornflowerblue;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
css3的计算属性,top、left的百分比是基于元素的左上角偏移,那么在减去自身一半的宽高就好了。
4.absolute + transform
.child{
height: 100px;
width: 100px;
background: cornflowerblue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
transform的translate属性也可以设置百分比,其是相对于自身的宽高,所以translate设置为(-50%,-50%),就可以做到水平垂直居中了。
5.text-align + lineheight + vertical-align
父元素添加样式
text-align: center;
line-height: 300px;
子元素添加样式
display: inline-block;
vertical-align: middle;
middle:元素上下边的中心点和行基线向上1/2x的高度位置对齐。

图中的红线是我认为的行高基线(这个知识点不太熟...)
6.css-table
.parent{
border: 1px solid cadetblue;
width:300px;
height:300px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child{
height: 100px;
width: 100px;
background: cornflowerblue;
display: inline-block;
}
7.flex
这是我最常用的一种方式,flex布局除了水平垂直居中外还有很多属性可以了解。
.parent{
display: flex;
justify-content: center;
align-items: center;
}
8.grid
css新出的网格布局 ,兼容性不太好。
.parent {
display: grid;
}
.child {
align-self: center;
justify-self: center;
}
总结
- PC端有兼容性要求,宽高固定,推荐absolute + 负margin
- PC端有兼容要求,宽高不固定,推荐css-table
- PC端无兼容性要求,推荐flex
- 移动端推荐使用flex