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.
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>
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With