css水平垂直居中块整理

1、绝对定位+负margin 

兼容性很好,但需要指定子块的高度和宽度,以及负margin

.wp{
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #ccc;
}
.test{
    height: 100px;
    position: absolute;
    top:50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    background-color: #edd;
    width: 100px;
}
<div class="wp">
    <div class="test"></div>
</div>


2、绝对定位加margin:auto

缺点:IE67不支持,需要指定子块的宽度和高度

.wp{
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #ccc;
}
.test {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
    height:100px;
    width: 100px;
    background-color: #edd;
}
<div class="wp">
    <div class="test"></div>
</div>

3、绝对定位+translate

不需要指定子块的高宽,当子块中无内容且未设置高宽,子块不可见。

IE6/7/8不支持

  .wp { 
      width:200px;
      height:200px; 
      background-color:yellow; 
      position:relative; 
  }
  .test { 
      left:50%; top:50%; 
      transform:translate(-50%,-50%); 
      -webkit-transform:translate(-50%,-50%); 
      background-color:gray; 
      color:white; 
      position:absolute; 
  }
<div class="wp">
    <div class="test">内容</div>
</div>

4、弹性盒

不需要指定子块的高宽,当子块中无内容且未设置高宽,子块不可见。

IE6/7/8/9不支持

.wp{
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align: center;
     -moz-box-align: center;
     -ms-flex-align: center;
  -webkit-align-items: center;
          align-items: center;
  -webkit-box-pack: center;
     -moz-box-pack: center;
     -ms-flex-pack: center;
  -webkit-justify-content: center;
          justify-content: center;
    height: 200px;
    width: 200px;
    background-color: #ccc;

}
.test{
background-color: #edd;
}
<div class="wp">
    <div class="test">内容</div>
</div>

5、table-cell

IE6/7不支持

.wp{
    width: 200px;
    height: 200px;
    display: table;
    background-color: #ccc;
}
.test {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
<div class="wp">
    <div class="test">内容</div>
</div>

原文地址:https://www.cnblogs.com/qianlegeqian/p/4310392.html