在我们开发的过程中经常会用到水平垂直居中的css,所有总结了三种常用的方式。
先创建好一个父盒子和一个子盒子。并将父盒子设置好绝对定位。
子绝父相!!!
<div class="box">
<div class="son">
</div>
</div>
.box{
position: relative;
width: 500px;
height: 500px;
background-color: antiquewhite;
margin: 0 auto;
}
方式一
.son{
position: absolute;
width: 100px;
height: 100px;
top: 50%;/*父盒子Y轴的一半*/
left: 50%;/*父盒子X轴的一半*/
margin-left: -50px;/*以子盒子自身X轴左移动一半*/
margin-top: -50px;/*以子盒子自身Y轴上移动一半*/
background-color: red;
}
方式二
常见的一种方式。
.son{
position: absolute;
width: 100px;
height: 100px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background-color: red;
}
方式三
利用变形 transform
来设置水平垂直居中。
.son{
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
/*盒子水平居中*/
transform: translate(-50%,-50%);
background-color: red;
}
和第一种方式类似,都是通过设置XY各一半,然后再对子盒子设置位移XY各一半来达到水平垂直居中。