其实实现水平垂直剧中方法有很多:
-
第一种思路:通过给div设置绝对定位,并且left,right,top,bottom设置为0,margin:auto即可以水平垂直居中
div{
width: 500px;
height: 500px;
background-color: skyblue;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
-
第二种思路:通过给div设置绝对定位,left为50%,top为50%,再给div设置距左是自身的一半即:margin-left:-自身宽度/2,margin-top:-自身高度/2。
div{
width: 500px;
height: 500px;
background-color: skyblue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -250px;
}
-
第三种思路:通过给div设置绝对定位,left为50%,top为50%,再给div设置跨左和跟上是自身的一半:transform:translate3d(-50%,-50%,0)
div{
width: 500px;
height: 500px;
background-color: skyblue;
position: absolute;
left: 50%;
top: 50%;
transform:translate3d(-50%,-50%,0)
}
-
flex布局:有两个div,父级div和子级div,给父级div设置display:flex,并且设置父级div的水平居中justify-content:center,并且给父级div设置垂直居中align-items:center
<div class="a">
<div class="b">123</div>
</div>
.a{
width: 500px;
height: 500px;
background-color: skyblue;
display: flex;
justify-content:center;
align-items:center;
}