vertical-align 的使用

segmentfault 看到这样一个问题, 问两个 display: inline-block; 的元素为什么不能对齐显示。 于是想到了使用 vertical-align 来解决。

vertical-align 仅适用于内联和表格单元格元素, 以下是两种常见用法

图片与文字的居中

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
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}

div {
width: 500px;
padding-left: 30px;
background-color: aqua;
height: 100px;
line-height: 100px;
}

img {
width: 80px;
height: 80px;
vertical-align: middle;
}

span {
font-size: 14px;
}
</style>
</head>

<body>
<div>
<img src="http://img1.gtimg.com/0/70/7064/706481_1800x1900_0.jpg">
<span>文字居中</span>
</div>
</body>

</html>

使 display: inline-block; 元素对齐显示

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
31
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}

.a,
.b {
display: inline-block;
width: 200px;
height: 200px;
border: 1px solid red;
vertical-align: middle;
}
</style>
</head>

<body>
<div class="a"></div>
<div class="b">ahjlfchvg</div>
</body>

</html>