为什么不垂直对齐:中间工作?然而,垂直对齐:顶部确实有效。

跨度{垂直对齐:中间;}<div><img src=“https://via.placeholder.com/30“alt=”小img“/><span>不起作用</span></div>


当前回答

您可以做的另一件事是将文本的行高度设置为<div>中图像的大小。然后将图像设置为垂直对齐:中间;

这是最简单的方法。

其他回答

不知道为什么它不在导航浏览器上显示,但我通常在尝试显示带有图像和居中文本的标题时使用这样的代码段,希望它有所帮助!

https://output.jsbin.com/jeqorahupo

            <hgroup style="display:block; text-align:center;  vertical-align:middle;  margin:inherit auto; padding:inherit auto; max-height:inherit">

            <header style="background:url('http://lorempixel.com/30/30/') center center no-repeat; background-size:auto; display:inner-block; vertical-align:middle; position:relative; position:absolute; top:inherit; left:inherit; display: -webkit-box; display: -webkit-flex;display: -moz-box;display: -ms-flexbox;display: flex;-webkit-flex-align: center;-ms-flex-align: center;-webkit-align-items: center;align-items: center;">

            <image src="http://lorempixel.com/60/60/" title="Img title" style="opacity:0.35"></img>
                    http://lipsum.org</header>
                    </hgroup>

例如,在jQuerymobile中的一个按钮上,您可以通过将此样式应用于图像来对其进行一些调整:

.btn-image {
    vertical-align:middle;
    margin:0 0 3px 0;
}

你可能想要这样:

<div>
   <img style="width:30px; height:30px;">
   <span style="vertical-align:50%; line-height:30px;">Didn't work.</span>
</div>

正如其他人所建议的,尝试在图像上垂直对齐:

<div>
   <img style="width:30px; height:30px; vertical-align:middle;">
   <span>Didn't work.</span>
</div>

CSS并不烦人。你只是没有阅读文档;P

2022年,浏览器支持率达到96%,我很惊讶没有人建议使用网格布局。

在本JSFiddle中,3行是实现OP目标所需的全部内容(但提供了多条路线以供比较):

div {
    display: grid;
    grid-template-columns: min-content max-content;
    align-items: center
}

一个额外的UI细节将包括可选的gap属性的使用,该属性允许调整父网格容器(div)中每个网格项之间的空间。

网格布局的优势

轻松垂直和水平对齐网格项网格项之间的空间调制任何大小的图像(使用最小内容)和文本长度(使用最大内容的一行或使用最小内容的换行(未在fiddle中显示))都可以工作-无需在CSS中硬编码图像尺寸(两种用法都在JSFiddle中演示)现代方法


网格布局的缺点

较旧的浏览器支持更具挑战性网格布局通常需要更有经验的开发人员来正确实现,而不是像块/内联块显示那样简单

将div更改为flex容器:

div { display: flex; }

Now there are two methods to center the alignments for all the content:

方法1:

div { align-items: center; }

DEMO


方法2:

div * { margin: auto 0; }

DEMO


尝试在img上使用不同的宽度和高度值,在跨距上尝试不同的字体大小值,您将看到它们始终保持在容器的中间。