CSS 如何实现垂直居中?

1
2
3
4
5
6
7
<!-- 示例html结构 -->

<div class="parent">
<div class="child">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis iusto praesentium dolorem qui, accusamus labore fugit nulla quibusdam eius explicabo minima libero, obcaecati, odio rerum quae inventore vel quo totam!
</div>
</div>

父元素 height 属性未写

1
2
3
4
5
6
7
8
9
10
/* 重点:父元素上下添加内边距即可 */
.parent{
padding: 50px 0;
}

.child {
border: 5px solid green;
margin: 0 50px;
}


父元素 height 属性已写

flex布局(推荐方案)

1
2
3
4
5
6
7
8
9
10
11
.parent {
border: 3px solid green
height: 400px;
display: flex;
justify-content: center;
align-items: center;
}
.child{
border: 3px solid green
width: 300px;
}

margin

1
2
3
4
5
6
7
8
9
10
11
12
13
.parent {
height: 400px;
position: relative;
}
.child {
width: 300px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px; /* 子元素 width 的一半 */
margin-top: -100px; /* 子元素 height 的一半 */
}

translate

1
2
3
4
5
6
7
8
9
10
11
.parent {
height: 400px;
position: relative;
}

.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

margin:auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.parent {
height: 400px;
position: relative;
}

.child {
width: 300px;
height: 200px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}

高度为 100% 的伪元素 + display: inline-block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.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% 高度中垂直居中 */
}

Table 方案

1. table

1
2
3
4
5
6
7
<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>
1
2
3
4
5
6
7
8
table {
border: 1px solid red;
height: 400px;
}

td {
border: 1px solid green;
}

2. div 模仿 table

1
2
3
4
5
6
7
8
9
.parent {
height: 400px;
display: table;
}

.child {
display: table-cell;
vertical-align: middle;
}

CSS 如何实现垂直居中?
http://example.com/2023/01/08/CSS基础 - 如何实现垂直居中?/
作者
Ray
发布于
2023年1月8日
许可协议