vertical-align属性设置元素的垂直对齐方式
对齐方式主要有以下几种:
vertical-align:text-top | 把元素顶端和父元素字体的顶端对齐 |
vertical-align:text-bottom | 把元素底端和父元素字体的底端对齐 |
vertical-align:top | 把元素顶端与行中最高元素的顶端对齐 |
vertical-align:middle | 把元素放置在父元素的中部 |
vertical-align:bottom | 把元素顶端与行中最低的元素的顶端对齐 |
<!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 type="text/css">
img {
width: 40px;
height: 40px;
}
img.top {
vertical-align: text-top
}
img.bottom {
vertical-align: text-bottom
}
img.center {
vertical-align: middle
}
</style>
</head>
<body>
<p>
这是一幅<img class="top" border="0" src="1.jpeg" />位于段落上的图像。
</p>
<p>
这是一幅<img class="bottom" border="0" src="1.jpeg" />位于段落下的图像。
</p>
</body>
</html>
效果如图:
例二:
做出如下效果图
代码实现:
<!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;
}
.box {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; /* 上面这五步是水平垂直居中 */
width: 630px;
height: 100px;
line-height: 100px;
border: 1px solid #ccc;
text-align: center;
}
.box span:nth-child(1) {
display: inline-block;
width: 232px;
height: 1px;
background: rgba(204, 204, 204, 1);
}
.box span:nth-child(2) {
display: inline-block;
height: 6px;
line-height: 6px;
/* vertical-align: -4px; */
}
.box span:nth-child(3) {
display: inline-block;
width: 232px;
height: 1px;
background: rgba(204, 204, 204, 1);
}
</style>
</head>
<body>
<div class="box">
<span></span>
<span>这几个字要居中显示</span>
<span></span>
</div>
</body>
</html>
效果图如下:
发现文字并不在横线的中间,原因是少了元素的垂直对齐方式,即中间注释掉的那个样式:
vertical-align: -4px;
加上之后即可实现