方案一 flex布局方式
<div class="father"><div class="son"></div></div>
.father {width: 200px;height: 200px;background-color: pink;display: flex;justify-content: center;align-items: center;}.son {width: 50px;height: 50px;background-color: yellow;}
看效果请点击案例
方案二 用text-align
.father {width: 200px;height: 200px;background-color: pink;text-align: center;line-height: 200px;}.son {display: inline-block;width: 50px;height: 50px;background-color: yellow;}
看效果请点击案例 如何让子盒子在父盒子中垂直居中-方法二
方案三 用子绝对父相对移动子盒子自身的一半
.father {width: 200px;height: 200px;background-color: pink;position: relative;}.son {width: 50px;height: 50px;background-color: yellow;position: absolute;left: 50%;top: 50%;margin-top: -25px;margin-left: -25px;}
看效果请点击案例 如何让子盒子在父盒子中垂直居中-方法三
方案四 子绝父相和外边距margin实现
.father {width: 200px;height: 200px;background-color: pink;position: relative;}.son {width: 50px;height: 50px;background-color: yellow;position: absolute;left: 0;top: 0;right: 0;bottom: 0;margin: auto;}
看效果请点击案例 如何让子盒子在父盒子中垂直居中-方法四
方案五子绝父相子位移实现
.father {width: 200px;height: 200px;background-color: pink;position: relative;}.son {width: 50px;height: 50px;background-color: yellow;position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);}
看效果请点击案例 如何让子盒子在父盒子中垂直居中-方法五
