图像旁文本垂直对齐的方法

图像旁文本垂直对齐的方法

技术背景

在网页设计中,经常需要将文本与图像进行垂直对齐。然而,由于HTML和CSS的特性,实现完美的垂直对齐可能会遇到一些挑战。本文将介绍多种实现图像旁文本垂直对齐的方法。

实现步骤

方法一:对图像应用垂直对齐

vertical-align:middle样式应用于图像:

1
2
3
4
<div>
<img style="vertical-align:middle" src="https://via.placeholder.com/60x60" alt="A grey image showing text 60 x 60">
<span>Works.</span>
</div>

方法二:使用Flexbox布局

1
2
3
4
.box {
display: flex;
align-items: center;
}
1
2
3
4
<div class="box">
<img src="https://via.placeholder.com/60x60">
<span>Works.</span>
</div>

其他垂直对齐技巧

单行文本垂直居中

设置文本元素的line-height等于容器的高度:

1
2
3
4
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>

多行文本垂直底部对齐

使用绝对定位:

1
2
3
<div style="position:relative;width:30px;height:60px;">
<div style="position:absolute;bottom:0">This is positioned on the bottom</div>
</div>

多行文本垂直居中

使用表格布局:

1
2
3
<div style="display:table;width:30px;height:60px;">
<div style="display:table-cell;height:30px;">This is positioned in the middle</div>
</div>

兼容旧版IE(<= 7)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<style type="text/css">
#container {
width: 30px;
height: 60px;
position: relative;
}
#wrapper > #container {
display: table;
position: static;
}
#container div {
position: absolute;
top: 50%;
}
#container div div {
position: relative;
top: -50%;
}
#container > div {
display: table-cell;
vertical-align: middle;
position: static;
}
</style>

<div id="wrapper">
<div id="container">
<div><div><p>Works in everything!</p></div></div>
</div>
</div>

可变容器高度的垂直居中

1
2
3
position: relative;
top: 50%;
transform: translateY(-50%);
1
2
3
4
<div style="display: flex; align-items: center;">
<img src="http://lorempixel.com/30/30/" alt="small img" />
<span>It works.</span>
</div>

核心代码

Flexbox布局

1
2
3
4
div {
display: flex;
align-items: center;
}
1
2
3
4
<div>
<img src="http://lorempixel.com/30/30/" alt="small img" />
<span>It works.</span>
</div>

表格布局

1
2
3
4
5
6
7
div {
display: table;
}
div * {
display: table-cell;
vertical-align: middle;
}
1
2
3
4
<div>
<img src="http://lorempixel.com/30/30/" alt="small img" />
<span>It works.</span>
</div>

最佳实践

  • 优先使用Flexbox布局,因为它简单且兼容性较好。
  • 如果需要兼容旧版浏览器,可以使用表格布局。
  • 在设置vertical-align时,确保元素为inlineinline-block

常见问题

  • vertical-alignspan标签上不生效span是内联标签,一些布局属性(如对齐、边距、内边距等)默认不生效。可以将其设置为inline-block
  • 在旧版IE中无法实现垂直对齐:可以使用特定的CSS hack来解决,如上述兼容旧版IE的代码。

图像旁文本垂直对齐的方法
https://119291.xyz/posts/vertically-align-text-next-to-an-image/
作者
ww
发布于
2025年5月16日
许可协议