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

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


当前回答

多线解决方案:

http://jsfiddle.net/zH58L/6/

<div style="display:table;width:30px;height:160px;">
    <img style="display:table-cell;width:30px;height:60px;padding:50px" src='...' />
    <div style="display:table-cell;height:30px;vertical-align:middle">
      Multiline text centered vertically
    </div>
</div>
<!-- note: img (height + 2x padding) must be equal to root div height -->

适用于所有浏览器和ie9+

其他回答

显示带对齐项目的柔性:居中;是垂直对齐项目的最佳方式

第二部分{显示:柔性;对齐项目:居中;}<div><img src=“https://via.placeholder.com/30“alt=”小img“/><span>它起作用</span></div>

使用行高度:30px作为跨度,以便文本与图像对齐:

<div>
  <img style="width:30px; height:30px;">
  <span style="line-height:30px;">Doesn't work.</span>
</div>

因为您必须将行高度设置为div的高度,这样才能工作

接受答案中使用的技术仅适用于单行文本(demo),而不适用于多行文本(demo),如这里所述。

如果有人需要将多行文本垂直居中放置到图像中,以下是几种方法(方法1和方法2受此CSS技巧文章启发)

方法#1:CSS表格(FIDDLE)(IE8+(犬))

CSS:

div {
    display: table;
}
span {
    vertical-align: middle;
    display: table-cell;
}

方法#2:容器上的伪元素(FIDDLE)(IE8+)

CSS:

div {
   height: 200px; /* height of image */
}

div:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

img {
    position: absolute;
}

span {
  display: inline-block;
  vertical-align: middle;
  margin-left: 200px;  /* width of image */
}

方法3:Flexbox(FIDDLE)(犬用)

CSS(上面的fiddle包含供应商前缀):

div {   
    display: flex; 
    align-items: center;    
}
img {
    min-width: 200px; /* width of image */
}

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

这是最简单的方法。