Vertically centering images in a DIV

By Paul Bagosy - December 13th, 2009

Have you ever needed to vertically center and image in a div only to realize that it’s nowhere near as easy as it is in a table with vertical-align:middle? Horizontal centering is easy, but that damnable vertical is always just out of reach. Sure, there are ways to make it look centered, but that flies out the window when you’re talking about dynamic sizes.

The work-around I use for this problem is to head a different route. I know I can’t center horizontally with a DIV, so I stop trying and learn to love the space. I just use a blank .gif the same height as my div and then use the style tag right on the IMG to set the background to my image with a position of center center. Viola, instant centered image!

<div style="height:200px; width:200px;"><img src="images/blank.gif" style="background:url(images/thumbnail.jpg) center center no-repeat;" alt="" /></div>
blank Vertically centering images in a DIV

Leave a Reply