Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical align middle on inline elements slightly off [duplicate]

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>
like image 790
Jonas Kohl Avatar asked Mar 10 '18 16:03

Jonas Kohl


People also ask

How do you center vertically inline elements?

You have two options. You can use CSS's padding to add padding top and bottom, to make the text appear in the middle. This is useful for multiline text. You can exploit the line-height property to make the text vertically centred.

How do I vertically center a div element?

Using the Line-Height Property In most cases, you can also center text vertically in a div by setting the line-height property with a value that is equal to the container element's height. Let's create the same div element with a yellow border around it as above.

How do you align inline elements?

To align things in the inline direction, use the properties which begin with justify- . Use justify-content to distribute space between grid tracks, and justify-items or justify-self to align items inside their grid area in the inline direction.


1 Answers

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>
like image 185
Bhuwan Avatar answered Sep 20 '22 02:09

Bhuwan