让元素水平垂直居中的几个方式

一、负margin前提是知道及(前提是知道元素的宽高)

       优点:兼容性好

       缺点:非响应式用法,内容可能会超出容器

<div class="aa"></div>
.aa{
    width: 100px;
    height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
        margin-top: -50px;
    margin-left: -50px;
    background-color: blue;
      }

二、transform法

优点:响应式布局,宽高可变

缺点:不支持IE8,提供前缀

<div class="a"></div>

.a{ 
    width: 50%;
    height: 20%;
    background: green;
    position: absolute;
    top:50%;
    left: 50%;
    transform:translate(-50%, -50%);
        -webkit-transform:translate(-50%, -50%);
        -ms-transform:translate(-50%, -50%);
}

三、flexbox

<div class="box">
    <div class="a"></div>
</div>

.box {
  height: 300px;
  width: 300px;
  background: red;
  display: -webkit-flex;
  display: flex;
  -webkit-align-items: center;
              align-items: center;
  -webkit-justify-content: center;
              justify-content: center;
}
.a{
   width: 200px;
   height: 200px;
   background: blue;
}

优点:兼容性好

<div class="a"></div>

#a{  
    width: 200px;
    height: 200px;
    background: red;
    margin:auto;
    position: absolute;
    top:0;left:0;right: 0;bottom: 0;
}

 

posted @ 2018-02-09 14:12  chwl  阅读(115)  评论(0编辑  收藏  举报