css垂直居中的几种方式

不定宽高

position: relative/absolute、translate

  • 兼容性
    • ie9+
  • 代码实现
.parent {
        position: relative;
        width:100%;
        height:100%;
    }
    
    .chirld {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%)
    }

复制代码

flex布局

  • 兼容性
    • ie10+
  • 代码实现
.parent {
    display:flex;
    justify-content:center;
    align-items:center
 }
复制代码

before伪元素

定宽高

position: fixed

  • 兼容性
    • ie7+
  • 代码实现
.parent {
        position: fixed;
        width: 100px;
        height: 100px;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin:auto;
    }
复制代码