以下是总结的九种实现垂直居中方式,清晰明了
居中元素定宽高适用👇
以下代码实现的效果均如此图所示:
1. absolute + 负margin
html:
<div class="parent">
<div class="child"></div>
</div>
css:
.parent {
position: relative;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
margin: -50px -50px;
/* */
background-color: green;
border: 1px solid red;
}
2. absolute + margin auto
html:
<div class="parent">
<div class="child"></div>
</div>
css:
.parent {
position: relative;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
/* */
background-color: green;
border: 1px solid red;
}
3. absolute + calc
html:
<div class="parent">
<div class="child"></div>
</div>
css:
.parent {
position: relative;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: calc(50% - 50px);
left: calc(50% - 50px);
/* */
background-color: green;
border: 1px solid red;
}
居中元素不定宽高适用👇
以下代码实现的效果均如此图所示:
4. flex
html:
<div class="parent">
<div class="child">123</div>
</div>
css:
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
/* */
background-color: green;
border: 1px solid red;
}
5. grid
html:
<div class="parent">
<div class="child">123</div>
</div>
css:
.parent {
display: grid;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
align-self: center;
justify-self: center;
/* */
background-color: green;
border: 1px solid red;
}
6. absolute + transform
html:
<div class="parent">
<div class="child">123</div>
</div>
css:
.parent {
position: relative;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* */
background-color:green;
border: 1px solid red;
}
7. table
html:
<table>
<tbody>
<tr>
<td class="parent">
<div class="child">123</div>
</td>
</tr>
</tbody>
</table>
css:
.parent {
width: 300px;
height: 300px;
text-align: center;
/* */
border: 1px solid red;
}
.child {
display: inline-block;
/* */
background-color: green;
border: 1px solid red;
}
8. line-height
html:
<div class="parent">
<div class="child">123</div>
</div>
css:
.parent {
line-height: 300px;
width: 300px;
text-align: center;
font-size: 0px;
/* */
border: 1px solid red;
}
.child {
font-size: 16px;
display: inline-block;
vertical-align: middle;
line-height: initial;
text-align: left;
/* */
background-color: green;
border: 1px solid red;
}
9. css-table
html:
<div class="parent">
<div class="child">123</div>
</div>
css:
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 300px;
height: 300px;
/* */
border: 1px solid red;
}
.child {
display: inline-block;
/* */
background-color: green;
border: 1px solid red;
}