1.使用绝对定位实现水平垂直居中
.center-vertical{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50%;
margin-left: -50%;
}
- 优点:兼容性好
- 缺点:需要提前知道元素的尺寸。如果不知道元素尺寸,就需要JS获取
2.使用transform代替margin
.center-vertical{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- 优点:无论元素尺寸是多少,它都可以水平垂直居中显示
- 缺点:兼容性不好
3.使用margin:auto;实现元素水平垂直居中
.center-vertical{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
4.弹性布局flex
.centent{
display: flex;
justify-content: center;
align-item: center;
}