不固定高宽 div 垂直居中的方法

1.方法一:伪元素和 inline-block / vertical-align(兼容 IE8)

.box-wrap{
      text-align: center
}
.box-wrap:before {
      content: '';
      display: inline-block;
      height: 100%;
      vertical-align: middle;
      margin-right: -0.25em; //微调整空格
}
.box {
     display: inline-block;
     vertical-align: middle;
}

方法二:flex(不兼容 ie8 以下)

.box-wrap {
     height: 300px;
     justify-content:center;
     align-items:center;
     display:flex;
     background-color:#666;
 }

方法三:transform(不兼容 ie8 以下)

 .box-wrap {
     width:100%;
     height:300px;
     background:rgba(0,0,0,0.7);
     position:relative;
}
.box{
    position:absolute;
    left:50%;
    top:50%;
    transform:translateX(-50%) translateY(-50%);
    -webkit-transform:translateX(-50%) translateY(-50%);
}

方法四:设置 margin:auto(该方法得严格意义上的非固定宽高,而是 50%的父级的宽高。)

.box-wrap {
    position: relative;
    width:100%;
    height:300px;
    background-color:#f00;
}
.box-content{
    position: absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
    width:50%;
    height:50%;
    margin:auto;
    background-color:#ff0;
}

内容来自https://mp.weixin.qq.com/s/Gnd7vngfS_ndk69hD2QHfg

原文地址:https://www.cnblogs.com/lwming/p/15183666.html