子盒子在父盒子里水平垂直居中的三种方式
```.father{
position: relative;
width: 500px;
height: 500px;
margin: 100px auto;
background-color: red;
}
.son{
width: 100px;
height: 100px;
background-color: pink;
/*实现水平垂直居中*/
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
- 第二种实现方式:定位 + transform(不需要知道子元素的宽高)
.father{
position: relative;
width: 500px;
height: 500px;
background-color: red;
margin: 150px auto;
}
.son{
width: 200px;
height: 200px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
``` .father{
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color: red;
}
.son{
width: 200px;
height: 200px;
background-color: blue;
}
- 第四种实现方式:margin:auto;实现绝对定位元素的水平方向居中
```.father{
position: relative;
width: 300px;
height: 300px;
background-color: deepskyblue;
}
.son{
width: 100px;
height: 100px;
background-color: pink;
/*实现水平垂直居中*/
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}