Thursday, February 1, 2007

Vertically align images

Ever tried to vertically align an image inside a div? I tried to find an easy solution for this problem but couldn't find anything that worked on the web, so here's the solution I found.

But first, let me go back to the problem. Imagine you're creating a photo gallery website. Being a Web 2.0 kind of guy you place the thumbnails inside divs, something like:

<div class="thumb">
<img src="mythumb.jpg" />
</div>


Your css might look something like:

.thumb {
width: 120px;
height: 120px;
}

.thumb img {
vertical-align: middle;
}


If your thumbs aren't all the same size (and 120x120) this approach will not work! All your thumbs will be top aligned instead of middle aligned.

The problem here is that the image is being aligned relatively to the height of the contents of the div rather than to the div height. To solve this problem we have to make sure the content of the div has the same height as the div itself.

The hack you can use to "fool" the div is to create an empty image with height 100%:

<div class="thumb">
<img width="0" height="100%" />
<img src="mythumb.jpg" />
</div>


The first image has no width nor source, to make sure it stays invisible. Because the height is 100% it will have the same height as the div (120px in this case). This means the content of the div has 120px height, so the "mythumb.jpg" image will be properly aligned.

I tried this trick with Firefox 2.0 and IE 7.0 and it worked fine. If you find any browser where this doesn't work, please let me know.
Post a Comment