让div垂直水平都居中三种办法


将 div 居中这样的任务既容易又困难。它非常易于理解,但您不知道该怎么做(尽管您可能在参加新兵训练营时看到过很多次)。

<section>
    <div class='centre'>
        test
    </div>
</section>

传统方法:
.centre {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

然后 flexbox 出现了:
.centre {
    display: flex;
    justify-content: center;
    align-items: center;
}

网格:
.centre {
    display: grid;
    place-items: center;
}