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;
}
.f1-container .container {
position: relative;
}
.f1-container .box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
.f2-container .container {
position: relative;
background: yellow;
}
.f2-container .box {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
background: gold;
}
.f3-container .container {
position: relative;
background: fuchsia;
}
.f3-container .box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: gold;
}
.f4-container .container {
display: flex;
justify-content: center;
align-items: center;
background: greenyellow;
}
.f4-container .box {
background: purple;
}
.f5-container .container {
display: flex;
background: dodgerblue;
}
.f5-container .box {
margin: auto;
background: darkgray;
}