如何将图像垂直居中在一条线上?
当图像小于行高时,将图标在线居中的最佳方法是什么?
例如(内联样式以便于阅读):
<div style="line-height: 20px">
<img style="width: 12px; height: 12px;"/>
Blah blah blah
</div>
Here's a jsFiddle example。此示例还说明了为什么 vertical-align: middle
不起作用。
我希望 img 相对于 div 的文本居中。也就是说,即使文本换行为多行,图像也会以单行为中心。理想情况下,该解决方案不会涉及在图像上设置边距/填充,即使我不知道行高也能工作。
我读过的东西:
如何使用 CSS 垂直对齐图像旁边的文本?(处理图像较大的情况,似乎不适用于此处)
< a href="http://phrogz.net/CSS/vertical-align/index.html" rel="noreferrer" title="理解vertical-align">理解vertical-align
What's the best way to center icons on a line when the images are smaller than the line height?
For example (styles inline for easier reading):
<div style="line-height: 20px">
<img style="width: 12px; height: 12px;"/>
Blah blah blah
</div>
Here's a jsFiddle example. This example also shows why vertical-align: middle
does not work.
I want the img to be centered against the text of the div. That is, even if the text wrapped to multiple lines, the image would be centered against a single line. Ideally, the solution would not involve setting margings/paddings on the image and would work even if I didn't know the line-height.
Things I've read:
How do I vertically align text next to an image with CSS? (deals with case where image is larger, doesn't seem to apply here)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题的原因是图像相对于 x-height 垂直居中周围的文字。这可以在放大的屏幕截图中清楚地看到,其中 基线 和 平均线:
无论您使用哪种字体大小或行高,图像都会以类似方式对齐。因此,从印刷意义上来说,图像实际上是正确垂直对齐的。但是,如果您想调整对齐方式,使图像中心更接近平均线,只需使用
margin-bottom
将其向上移动一点即可:0.25 em 的值相当合适根据我尝试时看起来不错的任意选择。根据口味自由调整。
这是边距调整前后的比较,字体大小不同。
The cause of your problem is that the image is vertically centered relative to the x-height of the surrounding text. This can be seen quite clearly on an enlarged screenshot where the baseline and mean line of the surrounding text is included:
The image is aligned similarly no matter which font size or line height you use. So, in a typographical sense, the image is actually correctly vertically aligned. However, if you'd like to adjust the alignment so that the center of the image is closer to the mean line, simply move it a bit upwards using
margin-bottom
:The value of 0.25 em is rather arbitrarily chosen, based on what looked good when I tried it out. Adjust freely according to taste.
Here is a comparison before and after the margin-adjustment, with different font sizes.
为什么不将图像设置为 div 元素的背景?即:
这会将图像放置在左上角。至少我会这么做。
问候
Why don't you set the image as background of the div element? I.e.:
This will position the image on the top left. At least that's how I would do.
Regards
尝试使父容器
display: table
和display: table-cell
。之后,vertical-align: middle
应该以“表格方式”工作。Try to make parents container
display: table
anddisplay: table-cell
. After thatvertical-align: middle
should work in "table way".