盒子宽高已知
- 子元素绝对定位+margin设置auto
.child{
width: 100px;
height: 100px;
background: #f00;
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
}
- 子元素绝对定位+margin设置负像素值
.child{
width: 100px;
height: 100px;
background: #f00;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
盒子宽高未知
宽高未知的方法同样适用于宽高已知的情况!
- 父元素使用弹性盒模型
.parent{
display: flex;
justify-content: center;
align-items: center;
}
- 子元素绝对定位+偏移
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}