繁体   English   中英

如何使用 display:inline-block 垂直对齐图像和文本?

[英]How to vertically align images and text with display:inline-block?

我正在尝试使图标很好地适应 HTML/CSS 中的文本。

看起来这应该可以通过display:inline-block; . 然而,由于幻像填充,这似乎总是出错:

<div style="">
    <div style="display:inline-block;">Text here</div><img style="height:24px;display:inline-block" src="{{ url_for('static', filename= 'images/icon-unsorted.png' ) }}" />
</div>

在此处输入图片说明

如您所见,外部 div 变为 25.64px high ,而它的两个子元素都是 24px high

此外,图像在底部对齐,而文本则与外部 div 的顶部对齐。

但是,我希望它们都垂直(居中)对齐。

如果我尝试将外部 div 强制为 24px<div style="height:24px;"> ,内容保持不正确对齐,并且图标只是在其父级下方溢出。

在此处输入图片说明

所以我想我的问题是这样的:

如何使图像很好地适合一行文本,其中图像与文本具有相同的高度,或者两者都垂直居中对齐?

我可能会尝试更面向 css 的方法。 我在下面做了一个小例子。

 .btnStyle { position: relative; display: inline-flex; width: 110px; height: 24px; text-align: left; font-family: Helvetica, sans-serif; color: black; background-image: url(https://extortionguild.com/images/icon-unsorted.png); background-size: 17.5px 100%; background-position: right center; background-repeat: no-repeat; margin-right: 20px; } table { position: absolute; top: 0; left: 0; height: 100%; width: calc(100% - 20px); font-size: 18px; } table td { vertical-align: middle; }
 <div style="display:inline-block; width: 100% height: 40px;"> <div class="btnStyle"><!-- Button 1--> <table> <tr> <td> Text here </td> </tr> </table> </div> <div class="btnStyle"><!-- Button 2--> <table> <tr> <td> Text here </td> </tr> </table> </div> <div class="btnStyle" style="width: 200px;"><!-- Button 3 - wider--> <table> <tr> <td> Even More Text here </td> </tr> </table> </div> </div>

• 使用类还允许您通过 btnStyle 类更改所有按钮,而不必单独更改每个按钮。

• 表格有一个“内置”的垂直对齐:中间; 选项,这是一种非常简单的方法,可以将任何单元格内容垂直居中对齐。 --文档

• 您需要将背景图片 url 编辑为 background-image: url(images/icon-unsorted.png); 加载您的图像文件。

development-ninja也在使用“flex”的正确轨道上,但它需要是“inline-flex”,否则他们会尝试堆叠。 -- 有关 inline-flex 浏览器支持信息,请单击此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM