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" />

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" />

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.


Anonymous said...

whaddaya know! it worked!

worth mentioning that you still need to apply the "vertical-align:middle" to both the invisible image and the actual image for this to work.

Anonymous said...

If we use this trick in I.E7,
in I.E7 it show in design the blank image(image missing).

In Mozilla it looks good.

Anonymous said...

Just link it to a clear gif instead and there will be no broken image icon.
I keep one in the image folder for all my sites... 1px X 1px transparent gif.

Sumayya said...

Good Idea

Bikash said...

I tried to use this concept to allign text in the center of the div vertically, This way I can align only one line of text. I tried adding a paragraph instead of image, the first line is OK but when the line wraps to second one it slides down the box leaving blank space in between. Do we have a way where we can puts a paragraph exactly at the center of the div with equal spacing from all four sides. just note i dont want to use padding and margin.

Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.

Vipul Mathur said...

In FF 3.x it is not working. but if you use a blank gif it works perfectly.
<img width="0" height="100%" src="images/blank.gif" />