0

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?

J-bob
  • 8,380
  • 11
  • 52
  • 85

3 Answers3

2

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 :)

Narek-T
  • 1,898
  • 10
  • 20
  • Ah yes, I'm an avid user of flexbox, but I'm generating html to be used in an email, and many email clients ignore flexbox. So I gotta hack my way around that. – J-bob Jan 28 '16 at 19:25
1

There a small space below every image. By default, an image is rendered inline (actually it's inline-block), like a letter. It sits on the same line that other letters sit on. There is space below that line for the descenders you find on letters like j, p and q.

You can adjust the vertical-align of the image to position it elsewhere. In this case vertical-align: middle; would be fine.

This answer describes the issue in details: Mystery white space underneath image tag

Community
  • 1
  • 1
Konstantine Kalbazov
  • 2,643
  • 26
  • 29
0

Vertical align is one of those things they never got quite right - try googling some articles around it.

My instant reaction here is to try vertical-align:middle on each of your images - but no guarantees - I've always had to experiment and you may get varying results from different browsers.

The only all-browser answer I've found is to create a 2-column table (maybe within the div box, but not necessarily) and put text in one cell (text is automatically vertically centred in table cells) then put the matching image in the next cell (which will automatically expand to the height of the image).

Aren't tables brilliant? (some people don't think so...)

Tony Duffill
  • 277
  • 1
  • 5