如未说明,HTML均使用如下模板
<div class="parent">
<div class="son"></div>
</div>
1.flex布局
.parent {
display: flex;
justify-content: center;
align-items: center;
}
2.position:absolute; + margin 负值 (需要固定宽高),负值分别为子元素宽高的一半
.parent {
position: relative;
width: 600px;
height: 600px;
}
.son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-top: -100px;
margin-left: -100px;
}
3. position:absolute; + transform: translate(-50%,-50%); 无需固定宽高
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4.position: absolute; margin:auto; 无需固定宽高
.son {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}