情况一:图片盒子高度小于文字盒子
实现效果:
步骤:
1.包含整体的div设置 display:table;(此元素会作为块级表格来显示(类似 <table>),表格前后带有换行符。) 。
2.将包含图片的div和包含文字的div分别设置 display:table-cell;(此元素会作为一个表格单元格显示(类似 <td>和 <th>)) ,此时图片和文字将处于同一行。
3.给包含文字的div设置 vertical-align:top;(把元素的顶端与行中最高元素的顶端对齐) ,实现文字向上对齐。
4.给包含图片的div设置 vertical-align: middle; (把此元素放置在父元素的中部。) ,实现图片相对于文字段落居中。
<!DOCTYPE html>
<html lang="zh-cmn-hans">
<head>
<meta charset="utf-8">
<title>图片居中 table-cell</title>
<style>
global-box {
display: table;
}
.img-box {
display: table-cell;
background-color: yellow;
vertical-align: middle;
}
.text-box {
display: table-cell;
background-color: #000;
vertical-align: top;
}
p {
background-color: lightblue;
}
</style>
</head>
<body>
<div class="global-box">
<div class="img-box">
<img class="image" src="i-7.png">
</div>
<div class="text-box">
<p>the first paragraph.</p>
<p>the second paragraph.</p>
<p>the third paragraph.</p>
</div>
</div>
</body>
</html>
情况二:图片盒子高度大于文字盒子
实现效果:
步骤:
将图片盒子和文字盒子的vertical-align属性值互换即可实现。
<!DOCTYPE html>
<html lang="zh-cmn-hans">
<head>
<meta charset="utf-8">
<title>图片居中 table-cell</title>
<style>
global-box {
display: table;
}
.img-box {
display: table-cell;
background-color: yellow;
vertical-align: top;
}
.text-box {
display: table-cell;
background-color: #000;
vertical-align: middle;
}
p {
background-color: lightblue;
}
</style>
</head>
<body>
<div class="global-box">
<div class="img-box">
<img class="image" src="i-7.jpg">
</div>
<div class="text-box">
<p>the first paragraph.</p>
<p>the second paragraph.</p>
<p>the third paragraph.</p>
</div>
</div>
</body>
</html>