简介4种CSS实现水平垂直居中的方法及优缺点

绝对定位居中 Absolute Centering

<div class="Container">  
  <div class="Absolute-Center">  
  </div>
</div>
  
.Container {
  position: relative;
}
.Absolute-Center {
  position: absolute;  
  width: 50%;
  height: 50%;
  overflow: auto; //防止内容越界溢出
  margin: auto;
  top: 0; left: 0; bottom: 0; right: 0;
}

优点:

  1. 兼容性好 Support IE8+

  2. 支持百分比宽高

缺点:

  1. 必须声明高度

  2. 不适用Windows Phone

负边距 Negative Margins

.is-Negative {
        position: absolute;
        width: 100px;
        height: 200px;
        padding: 10px;
        top: 50%; left: 50%;
        margin-left: -60px; //(width + padding)/2
        margin-top: -110px; //(height + padding)/2
}

优点:

  1. 兼容性好 Support All Browser

缺点:

  1. 定宽高且不支持百分比

表格单元 Table Cell

<div class="Container ">  
  <div class="Table-Cell">  
    <div class="Child">  
    </div>
  </div>
</div>

.Container {
  display: table;
}
.Table-Cell {
  display: table-cell;
  vertical-align: middle;
}
.Child {
  width: 50%;
  margin: 0 auto;
}

优点:

  1. 兼容性好 Support IE8+

  2. 不定宽高

缺点:

  1. html层级多

移动 Transform:Translate

.Transform-Translate {
  position: absolute;
  width: 50%;
  margin: auto;
  top: 50%; left: 50%;
  -webkit-transform: translate(-50%,-50%);
}

优点:

  1. 不定宽高

缺点:

  1. 浏览器兼容性(适合移动端)

  2. 厂商前缀

  3. 可能与其他transform属性冲突

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12210124.html