Skip to main content

垂直居中方案

<div class="container">
<div class="content">要垂直居中的内容</div>
</div>
.container {
width: 700px;
height: 300px;
background-color: #a7dbd8;
}

.content {
width: 30%;
height: 30%;
text-align: center;
background-color: #2fb45a;
}
Details

使用 Flexbox

.container {
width: 700px;
height: 300px;
background-color: #a7dbd8;

display: flex;
align-items: center;
}

.content {
width: 30%;
height: 30%;
text-align: center;
background-color: #2fb45a;
}
Details

使用绝对定位

.container {
width: 700px;
height: 300px;
background-color: #a7dbd8;

position: relative;
}

.content {
width: 30%;
height: 30%;
text-align: center;
background-color: #2fb45a;

position: absolute;
top: 50%;
transform: translateY(-50%);
/* 如果子元素的高度是固定的,可以使用 margin-top: -(height/2)px; */
}
Details

使用 Grid 布局

.container {
width: 700px;
height: 300px;
background-color: #a7dbd8;

display: grid;
/* place-items: center; 水平垂直居中 */
}

.content {
width: 30%;
height: 30%;
text-align: center;
background-color: #2fb45a;

align-self: center;
}
Details