如何使用 css 将浮动图像旁边的文本居中?
How do I center text next to a floating image using css?
<html>
<head>
<style type="text/css">
img{
float: left;
}
</style>
</head>
<body>
<img id="img" src="imgsource.jpg">
<h2> Text that should be next to the image. </h2>
<p> Text that should be below the image and heading. </p>
</body>
</html>
我遇到的问题是图片旁边的文字没有居中,当我希望下一段文字位于图片和标题下方时,它也会出现在图片旁边。
img {
vertical-align: middle;
width: 300px
}
h2{
display: inline;
}
p{
clear:both;
display: block;
}
<img id="img" src="http://dreamatico.com/data_images/kitten/kitten-3.jpg">
<h2> Text that should be next to the image. </h2>
<p>Text that should be below the image and heading.</p>
为此,您应该先稍微更改 HTML 结构:
<img id="img" src="https://placekitten.com/g/200/300">
<div id="text">
<h2> Text that should be next to the image. </h2>
</div>
<div class="clear"></div>
<p> Text that should be below the image and heading. </p>
然后在正确的元素上使用浮动,使它们彼此相邻:
img, #text{
float: left;
}
使用 display: table-cell
和 vertical align
您可以将文本垂直居中放置在图片旁边。 注意:您必须知道您的图片高度。
#text h2{
vertical-align: middle;
height: 300px;
display: table-cell;
padding-left: 10px;
}
最后,别忘了clear your floats,这样您的其余文字就会显示在图像下方。
.clear{
clear: both;
}
<html>
<head>
<style type="text/css">
img{
float: left;
}
</style>
</head>
<body>
<img id="img" src="imgsource.jpg">
<h2> Text that should be next to the image. </h2>
<p> Text that should be below the image and heading. </p>
</body>
</html>
我遇到的问题是图片旁边的文字没有居中,当我希望下一段文字位于图片和标题下方时,它也会出现在图片旁边。
img {
vertical-align: middle;
width: 300px
}
h2{
display: inline;
}
p{
clear:both;
display: block;
}
<img id="img" src="http://dreamatico.com/data_images/kitten/kitten-3.jpg">
<h2> Text that should be next to the image. </h2>
<p>Text that should be below the image and heading.</p>
为此,您应该先稍微更改 HTML 结构:
<img id="img" src="https://placekitten.com/g/200/300">
<div id="text">
<h2> Text that should be next to the image. </h2>
</div>
<div class="clear"></div>
<p> Text that should be below the image and heading. </p>
然后在正确的元素上使用浮动,使它们彼此相邻:
img, #text{
float: left;
}
使用 display: table-cell
和 vertical align
您可以将文本垂直居中放置在图片旁边。 注意:您必须知道您的图片高度。
#text h2{
vertical-align: middle;
height: 300px;
display: table-cell;
padding-left: 10px;
}
最后,别忘了clear your floats,这样您的其余文字就会显示在图像下方。
.clear{
clear: both;
}