内联元素的垂直对齐中间略微偏离

时间:2018-03-10 16:46:07

标签: html css flexbox vertical-alignment

当我尝试vertical-align: middle某个文字旁边的图标(<img>)时,图标总是有点太低(参见示例)。如何解决这个问题,使其垂直居中于文本。

实施例

p {
  font: 10pt Arial, sans-serif;
}

.icon {
  vertical-align: middle;
}
<p>This is some text with an <img src="https://i.imgur.com/IJs3M2P.png" class="icon" alt="Icon" width="16" height="16">icon in it.</p>

5 个答案:

答案 0 :(得分:4)

这是因为浏览器用户代理将默认line-height应用于元素...所以你必须使用一些vertical-align值...使用text-bottom

&#13;
&#13;
p {
  font: 10pt Arial, sans-serif;
}

.icon {
  vertical-align: text-bottom;
}
&#13;
<p>This is some text with an <img src="https://i.imgur.com/IJs3M2P.png" class="icon" alt="Icon" width="16" height="16">icon in it.</p>
&#13;
&#13;
&#13;

好吧如果你不想在vertical-align上花太多时间,请使用简单的flexbox

&#13;
&#13;
p {
  display: flex;
  align-items: center;
  font: 10pt Arial, sans-serif;
}
&#13;
<p>This is some text with an <img src="https://i.imgur.com/IJs3M2P.png" class="icon" alt="Icon" width="16" height="16">icon in it.</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试 vertical-align: text-top;

p {
  font: 10pt Arial, sans-serif;
}
.icon {
  vertical-align: text-top;
}
<p>This is some text with an <img src="https://i.imgur.com/IJs3M2P.png" class="icon" alt="Icon" width="16" height="16">icon in it.</p>

答案 2 :(得分:0)

添加到.icon

  position: relative;
  left: -2px;

这会将它从原来的位置向左移动两个像素。

&#13;
&#13;
p {
  font: 10pt Arial, sans-serif;
}
.icon {
  vertical-align: middle;
  position: relative;
  left: -2px;
}
&#13;
<p>This is some text with an <img src="https://i.imgur.com/IJs3M2P.png" class="icon" alt="Icon" width="16" height="16">icon in it.</p>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我认为这是您最好的解决方案:

.icon {
  vertical-align: middle;
  padding-bottom: 3px;
}

其他可能的解决方案:https://github.com/google/material-design-icons/issues/206

希望这会有所帮助;)

答案 4 :(得分:0)

p {
  font: 10pt Arial, sans-serif;
}
.icon {
  vertical-align: sub;
}
<p>This is some text with an <img src="https://i.imgur.com/IJs3M2P.png" class="icon" alt="Icon" width="16" height="16">icon in it.</p>