Applied CSS Vertical-Align

Sunday, April 9, 2006 by Nicholas Gagne

In my previous article, Vertical-Align Misuse, I went over the proper way to use the CSS vertical-align property. Since then, I've noticed a lot of situations were the vertical-align property still does not seem to work as expected, having a series of images with varying dimensions centered inside of fixed size containers being the most frequent situation. So, I have decided to write a follow-up article to demonstrate the way to solve this major problem, and hopefully bring some love back to vertical-align.

This is probably the most frequently talked about vertical-align problem I have heard, not just on this site, but all around the community. This is one of the main reasons people have given up on vertical-align, and instead using a series of margins and padding, or threatening Microsoft Internet Explorer to support the display:table properties (even though they should anyways.) Fear not! What I have here is a solution to this problem.

First, let's set up the basic html code to get things started:

<div>
    <img src="/images/demoBoxH.gif" alt="" />
</div>

Now we will add some CSS to give this div some shape, color, and center its contents horizontally (you know the CSS method that works as expected):

div{
    height:200px;
    width:200px;
    background:blue;
    text-align:center
}

In an ideal world you could just slap vertical-align:middle on the image and be done with it, like so:

img{
    vertical-align:middle
}

If that were the case, then you probably wouldn't be reading this. Since the vertical-align property is based off of the text layout properties of the parent element, we will use line-height equal to the height of our container:

div{
    height:200px;
    width:200px;
    background:blue;
    text-align:center;
    line-height:200px
}

That seems to work in most browsers, but of course not Internet Explorer. So, we add an equal amount of font-size and use a filter to reset non-Internet Explorer browsers:

div{
    height:200px;
    width:200px;
    background:blue;
    text-align:center;
    line-height:200px;
	font-size:200px
}
*>div{
	font-size:12px
}

That is all there is to it. The image is now appropriately placed in the center of the parent element. Now, add more images of varying dimensions and you will get the same result. View the vertical-align example page I've set up to see that this works in boxes of varying dimensions with images of varying dimensions. I hope this article allows you to welcome vertical-align back into your home.