垂直水平居中
1)知道了父元素的高度,直接可以使用 margin: 150px auto;
这样比较蠢,是自己计算出来的
2)(知道自己本身的宽高)使用绝对定位,让父元素设为相对定位,儿子设为绝对定位,然后left和top都设置为50%,再左移自己宽度的一半,上移自己高度的一半。
<div class="box1">
<div class="box2"></div>
</div>
.box1 {
position: relative;
}
.box2 {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
}
3)(不知道自己的宽高时)可以使用变形
transform: translate(-50%,-50%); /往回位移自己宽度和高度的一半/
.box1 {
width: 500px;
height: 500px;
background: red;
position: relative;
}
.box2 {
width: 200px;
height: 200px;
background: green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%); /*往回位移自己宽度和高度的一半*/
}
<div class="box1">
<div class="box2"></div>
</div>
4)使用弹性盒模型
父元素设置一下盒模型,让儿子位置为垂直水平
display: flex;
justify-content: center;
align-items: center;
<div id="box1">
<div id="box2"></div>
</div>
#box1 {
width: 500px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
}
#box2 {
width: 200px;
height: 200px;
background-color: red;
}