未知高宽的div在其父级div中垂直居中显示

(一)如果已知子div的高宽

.father {

  position: relative;

}

.child {

   100px;

  height: 80px;

  position: absolute;

  left: 50%;

  top: 50%;

  margin-left: -50px; // margin-left为宽度的一半

  margin-top: -40px; // margin-top为高度的一半

}

(二)、未知子div的高宽

.father {

  position: relative;

}

.child {

  position: absolute;

  left: 50%;

  top: 50%;

  -webkit-transform: translate(-50%, -50%);

  -moz-transform: translate(-50%, -50%);

  -o-transform: translate(-50%, -50%);

  transform: translate(-50%, -50%); // 原理:让子divX轴方向往左偏移一半自身宽度的距离,Y轴方向往上偏移自身一半高度的距离

}

原文地址:https://www.cnblogs.com/secretAngel/p/9699920.html