如何使用 CSS 垂直居中文本

如何使用 CSS 垂直居中文本

技术背景

在前端开发中,垂直居中文本是一个常见的需求。不同的布局场景和浏览器兼容性要求,需要不同的解决方案。本文将介绍多种使用 CSS 实现文本垂直居中的方法。

实现步骤

1. 单行文本基本方法

这种方法仅适用于单行文本,通过设置 line-height 等于容器高度来实现。

1
2
3
<div>
Hello World!
</div>
1
2
3
4
5
6
div {
height: 100px;
line-height: 100px;
text-align: center;
border: 2px dashed #f69c55;
}

2. 多行或单行文本通用方法

该方法适用于单行和多行文本,但需要固定高度的容器。

1
2
3
<div>
<span>Hello World!</span>
</div>
1
2
3
4
5
6
7
8
9
10
11
div {
height: 100px;
line-height: 100px;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: inline-block;
vertical-align: middle;
line-height: normal;
}

3. 模拟表格布局

模拟表格行为实现垂直居中,部分旧浏览器(如 IE7)可能不支持。

1
2
3
<div>
<span>Hello World!</span>
</div>
1
2
3
4
5
6
7
8
9
10
11
div {
display: table;
height: 100px;
width: 100%;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: table-cell;
vertical-align: middle;
}

4. 使用绝对定位

使用绝对定位结合 flexbox 布局实现垂直居中。

1
2
3
<div>
<span>Hello World!</span>
</div>
1
2
3
4
5
6
7
8
div {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100%;
border: 2px dashed #f69c55;
}

5. 使用 align-content 属性

在块级容器上使用 align-content 属性实现垂直居中。

1
2
3
<div id="box">
<div>Lorem ipsum dolor sit</div>
</div>
1
2
3
4
5
6
7
8
9
#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;
align-content: center;
}

6. 使用 Flexbox

在容器元素上添加 display: flex,并结合 justify-contentalign-items 属性。

1
2
3
<div class="box">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.box {
height: 150px;
width: 400px;
background: #000;
font-size: 24px;
font-style: oblique;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
justify-content: center;
align-items: center;
}

7. 使用 transform

通过 transform: translateY(-50%) 实现垂直居中。

1
2
3
<div class="element">
要居中的文本
</div>
1
2
3
4
5
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}

最佳实践

  • 兼容性考虑:对于需要兼容旧浏览器的项目,优先使用模拟表格布局或 transform 方法。
  • 响应式设计:在响应式布局中,建议使用 FlexboxGrid 布局,因为它们具有良好的灵活性和适应性。
  • 代码简洁性:尽量选择代码简洁、易于维护的方法,避免过度复杂的布局。

常见问题

  • 模糊问题:使用 transform: translateY(-50%) 时,元素可能会出现模糊现象。可以通过设置其父元素的 transform-style: preserve-3d 来解决。
1
2
3
4
5
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
  • 旧浏览器兼容性:部分方法在旧浏览器中可能不支持,如 display: flexdisplay: grid。可以使用浏览器前缀或备用方案来解决。
1
2
3
4
5
6
7
8
9
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

如何使用 CSS 垂直居中文本
https://119291.xyz/posts/2025-05-13.how-to-vertically-center-text-with-css/
作者
ww
发布于
2025年5月13日
许可协议