写在前面:
以下代码中,
.parent表示父元素,.child表示子元素。
当父元素没有写死高度时,子元素垂直居中是比较容易实现的,给父元素上下 padding 即可。如:
.parent {
padding: 50px 0;
}
不写死宽度和高度是比较好的习惯,建议尽量不要写死 width 和 height。
但有时不得不写死 width 或 height,以下是父元素 height 写死的情况下,让子元素垂直居中的几种方法。
1. flex
关键代码:
.parent {
height: 400px;
display: flex;
align-items: center;
}
2. absolute + translate -50%
关键代码:
.parent {
height: 400px;
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
3. absolute + 负 margin
关键代码:
.parent {
height: 400px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px; /* 子元素 width 的一半 */
margin-top: -100px; /* 子元素 height 的一半 */
}
4. absolute + margin: auto
关键代码:
.parent {
height: 400px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
5. table 标签
关键代码:
<table>
<tr>
<td>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora harum voluptates quae velit eveniet, accusamus, quas ratione placeat! Nisi perferendis facere, error sed possimus molestias et. Quas accusantium, maiores aliquid?
</td>
</tr>
</table>
6. div 模仿 table
关键代码:
.parent {
height: 400px;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
7. 高度为 100% 的伪元素 + display: inline-block
关键代码:
.parent {
height: 400px;
text-align: center;
}
.parent:before,
.parent:after {
content: "";
display: inline-block;
height: 100%; /* 前后伪元素高度 100% */
vertical-align: middle; /* 伪元素垂直居中 */
}
.child {
width: 300px;
display: inline-block;
vertical-align: middle; /* 子元素在 100% 高度中垂直居中 */
}