CSS 实现水平垂直居中
1.flex布局,无需考虑父子宽高 1
2
3
4/* 父元素设置 */
display: flex;
justify-content: center;
align-items: center;
2.相对定位+transform,无需考虑父子宽高 1
2
3
4
5/* 子元素设置 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
3.display:table-cell 1
2
3
4
5
6
7
8
9
10
11
12
13
14.parent {
width: 500px;
height: 500px;
background-color: pink;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
width: 200px;
height: 200px;
background-color: skyblue;
display: inline-block;
}1
2
3
4
5position: absolute;
top: 50%;
left: 50%;
margin-top: 手动计算;
margin-left: 手动计算;
5.magin auto,父元素宽高可以不确定,子元素没有具体宽高会铺满父元素
1
2
3
4
5
6position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
6.手动计算具体magin,父子元素宽高需要确定 1
2margin-top: 手动计算;
margin-left: 手动计算;