1.知道高度设置居中
.box1{
      border: 1px solid pink;
      height:300px;
      /* position: relative; */
    }
.box2{
      height: 100px;
      width: 100px;
      background-color: yellow;
      text-align: center;
      /* position: absolute;
      top:50%;
      left:50%;
      margin:-50px 0 0 -50px; */
      line-height:100px;          
     }
<div class="box1">
    <div class="box2">你好</div>
</div>
box2的高度为100px,所以设置line-height:100px,可以实现垂直居中的效果
![]()
2.未知高度设置居中
.box2{
        height: 50%;
        background-color: yellow;
        color: red;
               
    }
.box2::before{
        display: inline-block;
        content:"";
        height: 100%;
        vertical-align: middle;
    }
![]()
利用表格特性
.box2{
  display:table-cell;
  height:100px;
  width:100px;
  background:yellow;
  text-align:center;
  vertical-align:middle;
}