css3实现水平垂直居中的方式总结

水平垂直居中分为两种情况,一种是已知宽高的情况,第二种是未知宽高的情况
接下来以底下统一的html标签格式作为例子,css用的是stylus环境写的

<div class="main">
  <div class="test">
    <img src="@/images/common/loading_logo.gif">
  </div>
</div>

1.已知宽高

第一种情况,通过table实现水平垂直居中

这个有个注意事项,对table-cell元素设置百分比(如100%)的宽高值时无效的,但是可以将父元素设置display:table,再将父元素设置百分比宽高,子元素table-cell会自动撑满父元素。这就可以做相对于整个页面的水平垂直居中

    .main
        display table
        width 100%
        .test
          height:200px;
          display table-cell
          vertical-align middle
          text-align center
          img
            width:60px
            height:60px     

第二种情况,通过绝对定位,通过设置上下左右0,margin auto

    .test
      position relative
      width:100%
      height:200px;
      &>img
        position: absolute;
        width:60px;
        height:60px;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;   

第三种情况,还是绝对定位;将子元素left和right直接设为50%,相对的是父元素,然后在使用margin-left和margin-top设为子元素的一半的负数。就是将偏离父元素中心的那段拽回来;

<pre>
    .test
        height:200px;
        width:100%
        position:relative
        img
          width:60px;
          height:60px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-left: -30px;
          margin-top: -30px;  
</pre>

2.未知宽高

第一种情况,通过table实现水平垂直居中,和已知宽高通用
同上宽高的注意事项


.main
display table
width 100%
.test
height:200px;
display table-cell
vertical-align middle
text-align center

第二种情况,通过绝对定位,transform

     .main  
       .test
         position relative
         height:400px;
         &>img
           position: absolute;
           top 50%
           left 50%
           transform:translate(-50%,-50%)
   

第三种情况,flex盒子布局,加入display: -webkit-flex;是为了兼容性,有些旧的浏览器不兼容

       .main
           .test
             height: 200px;
             width: 100%;
             display:flex;
             justify-content: center;
             align-items: center;