垂直水平居中方式

99 阅读1分钟

个人觉得最常见、最简单的这四种方式:

Using flexbox

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

Using grid

.container {
    display: grid;
    place-content: center; // justify-content:center;align-content: center的简写
}

Using positions

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

// 方法2
.parent {
    position: relative;
}
.child {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

Using table-cell


.parent {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.child {
    display: inline-block;
}