垂直居中的几种方案

元素垂直居中,在网页中经常用到,现在总结几种常用的方案。

1.元素宽高固定居中

<div class=“test”>

测试文字

</div>

.test{500px;height:500px;position:fixed;left:50%;top:50%;margin-left:-250px;margin-top:-250px;}

这种在网页中经常用到,原理就是用margin负值宽高一半,来实现居中,但这种局限在宽高必须固定的情况下,一般适用于pc站

2.元素宽高不定居中

<div class=“test”>

测试文字

</div>

.test{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%)}

这种和上面原理类似,用到了css3的位移来达到居中的效果,推荐适用,但css3不兼容低版本浏览器,适用于移动端及主流浏览器,css3要加上浏览器前缀

3.适用flexbox来实现

css3不定宽高水平垂直居中

只要三句话就可以实现不定宽高水平垂直居中。

justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;
在父级元素上面加上上面3句话,就可以实现子元素水平垂直居中。

4,利用margin+position

div{position:relative;300px;height:300px;border:1px solid #ccc}

div p{position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;64px;height:60px;}

原文地址:https://www.cnblogs.com/he-qiang/p/5810903.html