网页元素div内垂直居中的若干种方法总结

Blog 1 // display:flex 方式
display: flex;
justify-content: center;
align-items: center;
 
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
 
.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
 
.parent {
    text-align: center;
    line-height: 300px; /* 等于 parent 的 height */
}
.child {
   display: inline-block;
   vertical-align: middle;
   line-height: initial; /* 这样 child 内的文字就不会超出跑到下面 */
}
 
.parent {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.child {
   display: inline-block;
}
 
// display:table-cell 方式
.parentElement {
  display: table;
  .childElement {
    display: table-cell;
    vertical-align: middle;
  }
  .grandsonElement {}
}
 
// 未知父元素高度
.parentElement {
  position: relative;
  // 方法1   transform: translateY(-50%);
  .childElement {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
  }
  // 方法2
  .childElement {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
  }
}
 
// 已知父元素高度,仅有一个子元素
.parentElement {
  height: xxx;
  .childElement {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
  }
}
 
// 伪元素:before
.parentElement {
  display: block;
  &:before {
    content: " ";
    display: inline-block;
    vertical-align: middle;
    height: 100%;
  }
  .childElement {
    display: inline-block;
    vertical-align: middle;
  }
}
 
// 隐藏节点
.parentElement {
  background: blue;
  width: 100%;
  height: 100px;
  .hide {
    width: 20%;
    height: 35%;//隐藏节点的高为 (父级高 - 去子级高)/2
  }
  .childElement {
    background: yellow;
    width: 20%;
    height: 30%;
  }
}