css中的垂直居中

absolute + margin-top

在子元素高度不变的情况下,可采用绝对定位和margin-top来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.demo-wapper-1 {
border: 1px solid #ccc;
height: 300px;
position: relative;
}
.demo-content-1 {
background-color: gray;
height: 100px;
width: 200px;
position: absolute;
top: 50%;
margin-top: -50px;
// 同时保持水平居中
left: 50%;
margin-left: -100px;
}
<div class="demo-wapper-1">
<div class="demo-content-1"></div>
</div>

line-height

当子元素为单行文本时,可以设置父元素的行高来保持垂直居中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.demo-wapper-2 {
border: 1px solid #ccc;
height: 200px;
line-height: 200px;
text-align: center
}

.demo-content-2 {
background-color: gray;
display: inline
}
<div class="demo-wapper-2">
<div class="demo-content-2"></div>
</div>

12345

vertical-align

方法一

使用tabletd来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.demo-table {
border: 1px solid #ccc;
height: 200px;
}
.demo-table td {
text-align: center;
vertical-align: middle;
}
<table class="demo-table">
<tr>
<td>
I'm vertically centered multiple lines of text in a real table cell.<br>
I'm vertically centered multiple lines of text in a real table cell.<br>
I'm vertically centered multiple lines of text in a real table cell.
</td>
</tr>
</table>

I’m vertically centered multiple lines of text in a real table cell.
I’m vertically centered multiple lines of text in a real table cell.
I’m vertically centered multiple lines of text in a real table cell.

方法二

模仿上面的形式,手动使用display:tabletable-cell来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.demo-wapper-3 {
border: 1px solid #ccc;
height: 200px;
width: 100%;
display: table;
}
.demo-content-3 {
background-color: gray;
height: 80px;
width: 200px;
text-align: center;
display: table-cell;
vertical-align: middle;
}
<div class="demo-wapper-3">
<div class="demo-content-3">1234<br>12345</div>
</div>

1234
12345

absolute + tranfrom

当我们不知道一个快块元素的高度时,可以使用tranfrom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.demo-wapper-4 {
border: 1px solid #ccc;
height: 200px;
position: relative;
}
.demo-content-4 {
background-color: gray;
height: 80px;
width: 200px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="demo-wapper-4">
<div class="demo-content-4"></div>
</div>



flex

在可以使用flex的时候,flex可能是比较好的选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.demo-wapper-5 {
border: 1px solid #ccc;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
}
.demo-content-5 {
background-color: gray;
height: 80px;
width: 200px;
}
<div class="demo-wapper-5">
<div class="demo-content-5"></div>
</div>

参考文档
Centering in CSS: A Complete Guide