在css中,要设置垂直居中主要有两种方式,一种是将元素设为绝对定位,然后利用top和margin来实现垂直居中;另一种是使用flex布局。以下分别进行介绍。
.parent {position: relative;}.child {position: absolute;top: 50%;margin-top: -25px; }.parent {display: flex;justify-content: center; align-items: center; }.child {width: 50px;height: 50px;}
需要注意的是,使用绝对定位时,父元素需要设置为相对定位;使用flex布局时,父元素需要设置为display:flex。此外,这两种方式可以同时使用,如:
.parent {position: relative;display: flex;justify-content: center;align-items: center;}.child {position: absolute;top: 50%;margin-top: -25px;width: 50px;height: 50px;}
以上就是css如何设置垂直居中的方法,希望对大家有所帮助。