- 定位法+margin(知道盒子实际宽高)
.parent {
position: relative;
width: 100%;
height: 100vh;
}
.box {
width: 100px;
height: 100px;
background: blueviolet;
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
2.定位+transform(无需知道盒子实际宽高)
.parent {
position: relative;
width: 100%;
height: 100vh;
}
.box {
width: 100px;
height: 100px;
background: blueviolet;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3.flex布局(父元素)
body {
position: relative;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 100px;
height: 100px;
background: blueviolet;
}
4.display: table-cell 无兼容性问题
.box {
width: 100px;
height: 100px;
background: blueviolet;
display: table-cell;
text-align: center;
vertical-align: middle;
}