实现盒子水平垂直居中的方法
实现的效果如下

<body>
<div class="father">
<div class="son"></div>
</div>
</body>
1、利用文本居中和行高实现
给父盒子设置文本居中text-align:center和行高line-height
将子盒子转为行内块元素,并设置vertical-align:middle
<style>
.father {
width: 300px;
height: 300px;
background-color: aqua;
text-align: center;
line-height: 300px;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
display: inline-block;
vertical-align: middle;
}
</style>
2、利用定位+外边距
利用子绝父相
1、给子盒子设置四个方向的位移均为0,外边距margin设为auto
.father {
width: 300px;
height: 300px;
background-color: aqua;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
2、给子盒子设置top:50% left:50% 让子盒子相距父盒子上边界,左边界宽高的50%
再利用 margin-top margin-left返回子盒子自身宽高的50%
.father {
width: 300px;
height: 300px;
background-color: aqua;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
/* 父盒子高度的一半 */
top: 50%;
left: 50%;
/* 自身高度的一半 */
margin-top: -50px;
margin-left: -50px;
}
3、利用定位+平移
利用子绝父相,给子盒子设置top和left移动父盒子宽高的50%,再利用平移,返回自身宽高的50%
.father {
width: 300px;
height: 300px;
background-color: aqua;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
4、利用flex布局
给父盒子设置display:flex,justify-content:center(主轴居中)、align-items:center(交叉轴居中)
.father {
width: 300px;
height: 300px;
background-color: aqua;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
}