未知尺寸元素水平垂直居中

未知尺寸元素水平垂直居中,一般都是针对行内元素。

知识点:水平居中text-align:center,垂直居中vertical-align:middle

一,使用display:table布局实现——兼容IE8

使用table来实现垂直居中,单元格默认样式 vertical-align:middle,所以 table-cell里面的内容会垂直居中。

    <style>
        #table{
            display: table;
            width: 100%;
            height:200px;
            text-align:center;
            color: #fff;
            background: #2f994c;
        }
        #table span{
            display: table-cell;
            vertical-align: middle;
        }
    </style>
<div id="table">
    <span>未知宽高水平垂直居中内容</span>
</div>

二,使用空标签或者伪类:after实现——兼容IE6

     #after{
            height:200px;
            text-align:center;
            color: #fff;
            background: #2688a8;
        }
        #after:after,#after .after{
            content:'';
            display:inline-block;
            vertical-align: middle;
            width:0;
            height:100%;
            /*兼容ie6*/
            *display:inline;
            *zoom:1;
        }
        #after span{
            display:inline-block;
            vertical-align:middle;
            /*兼容ie6*/
            *display:inline;
            *zoom:1;
        }
<div id="after">
    <span>未知宽高水平垂直居中内容</span>
    <!--[if lt IE 8]><span class="after"></span><![endif]-->
</div>

三,css3 transform: translate(-50%,-50%)实现

   #css3{
            position: relative;
height: 300px; } #css3 span{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
<div id="css3"> <span>未知宽高水平垂直居中内容</span> </div>

 

   #css3{
            position: relative;
      }
     #css3 span{
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
        }
posted @ 2016-12-16 16:46  minimal虾米  阅读(104)  评论(0编辑  收藏  举报