先定义两个盒子
<div class="father">
<div class="son"></div>
</div>
定位+margin |transfrom
利用“子绝父相”,子元素设置left:50%和top:50%,此时子元素左上角就到达父元素中心位置,在通过margin-top和margin-left,值为宽高的一般,这样一来,子元素版心位置能过在父元素内部居中,该方法需要给子元素设定宽高,因为margin需要具体的值。或者将margin去掉,改成transfrom,这样就不需要给定宽高了
.father{
position: relative;
width: 100%;
height: 100vh;
background-color: skyblue;
}
.son {
position: absolute;
width: 200px;
height: 200px;
background-color: pink;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
/* transform: translateX(-50%) translateY(-50%); */
}
第二种方法:利用“子绝父相”,再将子元素个个方向定位为0,最后margin:auto 进行平分,这样一样就实现了居中,该方法盒子有宽高
.father {
position: relative;
width: 100%;
height: 100vh;
background-color: skyblue;
}
.son {
position: absolute;
left: 0;
top:0;
right: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: pink;
}
flex布局
通过flex布局,将主轴居中,侧轴居中,高度默认为父元素高度,定不定义宽高都行
flex布局,主轴居中,侧轴居中
.father {
display: flex;
width: 100%;
height: 100vh;
background-color: skyblue;
justify-content: center;
align-items: center;
}
.son {
width: 200px;
height: 200px;
background-color: pink;
}
flex+margin
让父元素flex布局,子元素margin:auto 水平竖直平分即可,可不定义宽高
.father {
display: flex;
width: 100%;
height: 100vh;
background-color: skyblue;
}
.son {
margin: auto;
width: 200px;
height: 200px;
background-color: pink;
}
以上就是盒子水平垂直居中方法了,如果您还有其它方法,欢迎在评论区留言分享
如果有错误,请您指出,感谢您的阅读