两个盒子,父容器和子容器。实现子容器在父容器中垂直水平居中。效果如图:
<div class="big">
<div class="small">
</div>
</div>
image.png
方法如下:
1、设置position ,配合margin,子容器相对定位时每个方向都需要设置距离为0
.big{
height: 200px;
width: 200px;
background: pink;
position: relative;
}
.small{
height: 100px;
width: 100px;
background-color: lightblue;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
2.父容器依然是position: relative;
主要是子容器使用margin 偏移自身宽高的一半
.small{
height: 100px;
width: 100px;
background-color: lightblue;
position:absolute;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
}
3. 子容器中使用transform:translate()
原理同2
position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
4.使用flex,在父容器中设置flex属性。此时两个容器都不需要设置position属性了
.big{
height: 200px;
width: 200px;
background: pink;
display: flex;
justify-content: center;
align-items: center;
}
5.旧版本的flex实现
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align:center ;