水平居中和垂直居中方法总结

基本方法

1.已知宽度块元素宽度

.child{width:1000px;margin:0 auto;}

2.文本内容居中

.parent{text-align:center;}

3.文本垂直居中

.child{height:20px;line-height:20px}

综合使用

1.已知尺寸,设置position: absolute方法

.parent {position:relative;}
.child {
    position:absolute;
    top:50%;
    left:50%;
    width:150px;
    height:150px;
    margin-left:-75px;
    margin-top:-75px;
}

2.未知尺寸,设置position: absolute方法

.parent{position:relative;}
.child{
    position:absolute;
    top:50%;
    left:50%;
    -webkit-transform:translateX(-50%);
    transform:translateX(-50%);
    -webkit-transform:translateY(-50%);
    transform:translateY(-50%);
}

3.设置position: absolute方法,各方向均设置为0

content { 
    position:absolute; 
    top:0; 
    bottom:0;
    left:0; 
    right:0; 
    margin:auto; 
    height:240px; 
    width:70%; 
}

4.display: table-cell属性

.parent {
  height: 100px;
  width: 100px;
  background: #eee;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.child {
  color: red;
  background: red;
  display: inline-block;
}

5.display: flex属性

.parent{
  display:flex;
  justify-content:center;
  align-items:center;
}