CSS技巧-01 如何实现一个元素在页面中水平垂直居中?

(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;
}