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

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


当前回答

background:url(../images/red_bullet.jpg) left 3px no-repeat;

我通常用3px代替top。通过增加/减少该值,可以将图像更改为所需的高度。

其他回答

在css中使用flex属性。

通过在flex中使用对齐项将文本垂直居中对齐:居中;如果要通过在flex中使用“对齐内容:中心;”将文本水平居中对齐;。

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

在css中使用表单元格。

第二部分{显示:表格;}第二部分*{显示:表格单元格;垂直对齐:中间;}<div><img src=“http://lorempixel.com/30/30/“alt=”小img“/><span>它起作用了</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的高度,这样才能工作

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

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