CSS实现图片与文本的居中对齐的常见方式

32次阅读

共计 1701 个字符,预计需要花费 5 分钟才能阅读完成。

1. 为图片和文本都设置 vertical-align:middle<!DOCTYPE <!DOCTYPE html><html><head>
<meta charset=”utf-8″ />
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Page Title</title>
<style>
.d1>* {
vertical-align: middle;
}
</style>
</head>
<body>
<div class=’d1′>
<img src=’./1.jpg’ width=’100’/>
<span> 这是一段文本 </span>
</div>
</body></html>
2. 通过弹性布局实现,外层容器设置弹性布局,通过 align-items: middle 设置交叉轴居中对齐 <!DOCTYPE <!DOCTYPE html><html><head>
<meta charset=”utf-8″ />
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Page Title</title>
<style>
.d1 {
display: flex;
align-items: center;
}
</style>
</head>
<body>
<div class=’d1′>
<img src=’./1.jpg’ width=’100’/>
<span> 这是一段文本 </span>
</div>
</body></html>
3. 借助于背景图片实现,这时只需要文本居中即可 <!DOCTYPE <!DOCTYPE html><html><head>
<meta charset=”utf-8″ />
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Page Title</title>
<style>
.d1 {
height: 133px;
background: url(./1.jpg) 0 0 no-repeat;
background-size: 100px 133px;
padding-left: 100px;
line-height: 133px;
}
</style>
</head>
<body>
<div class=’d1′>
<!–<img src=’./1.jpg’ width=’100’/>–>
<span> 这是一段文本 </span>
</div>
</body></html>
4. 图片与文本左浮动,同时设置容器元素的 line-height<!DOCTYPE <!DOCTYPE html><html><head>
<meta charset=”utf-8″ />
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Page Title</title>
<style>
.d1 *{
float: left;
}
.d1 span {
line-height: 133px;
}
</style>
</head>
<body>
<div class=’d1′>
<img src=’./1.jpg’ width=’100′ height=’133’/>
<span> 这是一段文本 </span>
</div>
</body></html>
最终效果:
屏幕剪辑的捕获时间: 2018/10/11 23:37
5. 文本设置为行内块,图片垂直居中对齐 <html><head>
<meta charset=”utf-8″ />
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Page Title</title>
<style>
.d1 img {
vertical-align: middle;
}
.d1 span {
display: inline-block;
}
</style>
</head>
<body>
<div class=’d1′>
<img src=’./1.jpg’ width=’100′ height=’133’/>
<span> 这是一段文本 </span>
</div>
</body></html>

正文完
 0