css实现垂直居中的6种方法(代码示例)

2020-07-23 18:09:09
本篇文章给大家带来的内容是介绍css实现垂直居中的6种方法(代码示例)。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。

html结构

<p class="box box2">    <span class="content content2">垂直居中</span></p>

默认css样式结构

.box{    width:200px;    height:200px;    background-color:green;   }.content{    background-color:yellow;   }

1. table-cell

该方法兼容IE8+,火狐,谷歌,并且content是否有宽高都可以。 注:IE8+ 包含 IE8

.box2{    display:table-cell;      //此元素会作为一个表格单元格显示(类似 <td> 和 <th>)    text-align:center;       //左右居中    vertical-align:middle;   //上下居中        }

2. display: flex;

该方法不兼容IE8,IE9content是否有宽高都可以。兼容火狐、谷歌

参考flex布局:https://www.cnblogs.com/qingchunshiguang/p/8011103.html


.box2{    display: flex;    justify-content:center;  //左右居中    align-items:center;      //上下居中}

3. 绝对定位和负边距

该方法兼容IE8+,火狐,谷歌,content必须有宽高

.box2{    position:relative;}.content2{    position:absolute;    top:50%;    left:50%;    margin-top:-40px;    margin-left:-40px;}

4. 绝对定位和0

该方法兼容IE8+,火狐,谷歌,content必须有宽高。

.box2{    position:relative;}.content2{    margin:auto;    position:absolute;    top:0;    left:0;    right:0;    bottom:0;}

5. 绝对定位和transform

该方法不兼容IE8,兼容IE9+,火狐,谷歌,content是否有宽高都可以。

.box2{    position:relative;}.content2{    position:absolute;    top:50%;    left:50%;    transform:translate(-50%,-50%);}

6. display:flex 和 margin:auto

content有宽高:不兼容IE8,IE9,content没有宽高:不兼容IE。有无宽高都兼容火狐、谷歌。

.box2{    display: flex;    text-align: center;}.box2 .content2{margin: auto;}