写在前面

在实际开发过程中,我们会碰到很多需要用到水平垂直居中的场景,为了方便大家的开发,特此做下总结和记录。话不多说,进入正题(温馨提示:以下所说的居中是相对于父盒子而言)。

1.父盒子使用flex布局控制子盒子水平垂直居中

例如:

html部分:

1
2
3
<div class="parent">
<div class="son"></div>
</div>

css部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
.parent {
height: 300px;
width: 300px;
background-color: deepskyblue;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 100px;
height: 100px;
background-color: hotpink;
}

效果如下:

2.需要居中的盒子自身使用定位配合margin

html部分:

1
<div class="center"></div>

css部分:

1
2
3
4
5
6
7
8
9
10
11
.center {
background-color: deepskyblue;
width: 100px;
height: 100px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}

值得注意的是,这里的margin:auto;并不能省略,切记!!!

3.定位结合transform的translate属性

1
2
3
4
5
6
7
8
9
.center {
background-color: deepskyblue;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}