需求:子盒子在父盒子中水平垂直居中
效果图如下:
结构代码:
<div class="father">
<div class="son"></div>
</div>
第一种实现方式:定位 + 偏移
.father{
width: 300px;
height: 300px;
background-color: deepskyblue;
margin: 100px auto;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: pink;
/*实现水平垂直居中*/
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
第二种实现方式:定位 + transform(不需要知道子元素的宽高)
.father{
width: 300px;
height: 300px;
background-color: deepskyblue;
margin: 100px auto;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: pink;
/*实现水平垂直居中*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
第三种实现方式:让父盒子为flex容器
.father{
width: 300px;
height: 300px;
background-color: deepskyblue;
display: flex;
justify-content: center;
align-items: center;
}
.son{
width: 100px;
height: 100px;
background-color: pink;
}
第四种实现方式:margin:auto;实现绝对定位元素的水平方向居中
.father{
width: 300px;
height: 300px;
background-color: deepskyblue;
position: relative;
}
.son{
width: 100px;
height: 100px;
background-color: pink;
/*实现水平垂直居中*/
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}