让一个元素垂直水平居中
<div class='box'>
<div class='small_box'></div>
</div>
方法一: 子绝父相,top:50%,left:50%,子需要移动本身宽度和高度的一般
.box {
width: 400px;
height: 400px;
background: red;
position: relative;
}
.small_box {
width: 200px;
height: 200px;
background: yellow;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
方法二 :父元素设置成弹性盒子,子元素横向居中,纵向居中
.box {
width: 400px;
height: 400px;
background: red;
display: flex;
align-items: center;
justify-content: center;
}
.small_box {
width: 200px;
height: 200px;
background: yellow;
}
方法三 :子绝父相,子元素所有定位为0,margin设置auto自适应
.box {
width: 400px;
height: 400px;
background: red;
position: relative;
}
.small_box {
width: 200px;
height: 200px;
background: yellow;
position: absolute;
top: 0;
left: 0;
right: 0;
botttom: 0;
margin: auto;
}