css水平垂直居中有哪些,写出代码?

1.已知固定宽高元素

.parent {
    position: relative;
}
.child {
    width: 300px;
    height: 100px;
    padding: 20px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -70px 0 0 -170px;
}

2. 未知宽高元素

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

3.使用flex布局

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}

4.利用grid布局

.parent {
  height: 140px;
  display: grid;
}
.child { 
  margin: auto;
}
THE END