SOURCE

console 命令行工具 X clear

                    
>
console
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>实现垂直居中的几种方法</title>
</head>

<body>
    <section class="f1-container">
        <div class="container">
            <div class="box"></div>
        </div>
    </section>

    <section class="f2-container">
        <div class="container">
            <div class="box"></div>
        </div>
    </section>

    <section class="f3-container">
        <div class="container">
            <div class="box"></div>
        </div>
    </section>

    <section class="f4-container">
        <div class="container">
            <div class="box"></div>
        </div>
    </section>

    <section class="f5-container">
        <div class="container">
            <div class="box"></div>
        </div>
    </section>
</body>
</html>
section {
    margin: 10px;
}
.container {
    width: 300px;
    height: 300px;
    background: pink;
    border: 1ps solid red;
    margin: 0 auto;
}
.box {
    width: 100px;
    height: 100px;
    background: darkblue;
    border-radius: 5px;
    border: 1px solid darkorange;
}

.f1-container .container::before {
    content: '1';
    display: block;
}

.f2-container .container::before {
    content: '2';
    display: block;
}

.f3-container .container::before {
    content: '3';
    display: block;
}

.f4-container .container::before {
    content: '4';
    display: block;
    align-self: flex-start;
}

.f5-container .container::before {
    content: '5';
    display: block;
}

/* 第一种 start */
.f1-container .container {
    position: relative;
}

.f1-container .box {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
/* 第一种 end */

/* 第二种 start */
.f2-container .container {
    position: relative;
    background: yellow;
}

.f2-container .box {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
    background: gold;
}
/* 第二种 end */

/* 第三种 start */
.f3-container .container {
    position: relative;
    background: fuchsia;
}

.f3-container .box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: gold;
}
/* 第三种 end */

/* 第四种 start */
.f4-container .container {
    display: flex;
    justify-content: center;
    align-items: center;
    background: greenyellow;
}

.f4-container .box {
    background: purple;
}
/* 第四种 end */

/* 第五种 start */
.f5-container .container {
    display: flex;
    background: dodgerblue;
}

.f5-container .box {
    margin: auto;
    background: darkgray;
}
/* 第五种 end */