(1)知道子元素的宽高

<!--父元素相对定位-->
<!--子元素绝对定位-->
.child{
      position:absolute;
      top:50%;
      left:50%;
      margin-left:-50px;
      margin-top:-50px;
}

 (2)不考虑子元素的宽高

<!--父元素不能有定位-->
<!--子元素绝对定位-->
.child{
      position:absolute;
      top:0;
      left:0;
      right:0;
      bottom:0;
      margin:auto;
    }

 (3)不用考虑子元素的宽高,且当子元素没有宽高也能居中(兼容性不是很好)

<!--父元素不能有定位-->
<!--子元素绝对定位-->
.child{
      background-color: tomato;
      position:absolute;
      top:50%;
      left:50%;
      transform: translate(-50%,-50%);
    }

 (4)给父元素设置display:flex

body{
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
}

 (5)通过JS实现:

获取当前屏幕的宽高,通过DOM添加css样式达到效果

(6)父元素有固定宽高

同时父元素设置:

body{
      height: 988px; width: 1000px;
      display:table-cell;
      vertical-align: middle;
      text-align: center;
    }
子元素需要设置为inline-block
.child{
      display: inline-block;
}

 

相关文章:

  • 2021-12-06
  • 2021-12-31
  • 2022-12-23
  • 2021-06-01
  • 2021-08-03
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
猜你喜欢
  • 2022-01-14
  • 2021-11-21
  • 2022-12-23
  • 2021-08-31
  • 2022-02-08
  • 2022-12-23
  • 2022-01-02
相关资源
相似解决方案