让元素水平和垂直居中的方法总结

1.绝对定位和固定定位的方法

.div1{
  100px;
  height:100px;
  position:absolute;
  left:50%;
  top:50%;
  margin-left:-50px;
  margin-top:-50px;
  background: red;
}

2.绝对定位和固定定位加margin:auto实现

.div1{
  position:absolute;
  100px;
  height:100px;
  margin:auto;
  left:0;
  top:0;
  right:0;
  bottom:0;
  background: green;
}

3.table-cell实现

   .box{
             300px;
            height: 300px;
          display: table-cell;
            vertical-align: middle;
            text-align: center;
            border:1px solid #000;
        }
.box div{
          100px;
            height:100px;
            margin:0 auto;
            background-color:red;
        }

4.针对行内元素

div{
        height:100px;
        text-align:center;
        line-height:100px;
    }

5.利用css3的属性flex

.box{
   500px;
  height: 500px;
  display:flex;
  justify-content:center;
  align-items:center;
  border: 1px solid #666;
}
.div1{
  100px;
  height:100px;
  background-color:red;
}

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

原文地址:https://www.cnblogs.com/dglblog/p/8572378.html