7

When I try to vertical-align: middle an icon (<img>) next to some text, the icon is always a little bit too low (see example). How can I fix this so it is vertically centered with the text.

Example:

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>
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
Jonas Kohl
  • 1,018
  • 1
  • 11
  • 28
  • Well try some of the other possible values, easy enough to directly see what effect they have when you manipulate this in your browser dev tools ... – CBroe Mar 10 '18 at 16:49

5 Answers5

6

Well this is because a default line-height is applied to the elements by browsers user agent...So you have to play with some vertical-align values...use text-bottom

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

.icon {
  vertical-align: text-bottom;
}
<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>

Well If you don't want to spend too much time on vertical-align, use simply flexbox

p {
  display: flex;
  align-items: center;
  font: 10pt Arial, sans-serif;
}
<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>
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
1

Try 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>
Anzil khaN
  • 1,974
  • 1
  • 19
  • 30
0

Add to .icon

  position: relative;
  left: -2px;

This will move it two pixels to the left from where it originally was.

p {
  font: 10pt Arial, sans-serif;
}
.icon {
  vertical-align: middle;
  position: relative;
  left: -2px;
}
<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>
Orry
  • 659
  • 6
  • 21
0

I think that this is your best solution:

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

Other possible solutions: https://github.com/google/material-design-icons/issues/206

Hope this helps ;)

Tostifrosti
  • 143
  • 9
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>
Michelangelo
  • 5,888
  • 5
  • 31
  • 50