Search code examples
htmlcssvertical-alignment

Why is the img tag screwing up the vertical alignment from line-height?


I'm trying to vertically align some text in a div by setting the line height equal to the div height. This works just fine when there's just text in the div, and also when there's a small image in the div. But for some reason, when there's an image beyond a certain size in the div, it starts pushing the text downward. Check out this fiddle I made to demonstrate it.

In the fiddle are 4 divs that all have height: 40px and line-height:40px. The only difference is the the 2nd, 3rd & 4th divs also have images of size small, medium and large:

 .small{height:20px;}
 .medium{height:30px;}
 .large{height:40px;}

So why are the third fourth images messing up the vertical alignment?


Solution

  • You need to add vertical-align: middle to your img tag, because it's not inline element, its inline-block element.

    See updated Fiddle

    Note that your vertical alignment method will not work when your text will be more than 1 row. Use for alignments flexbox, there are really good things :)