Web Hosting Talk







View Full Version : CSS Vertically Aligning Image in DIV - Help!


DavetheWave
03-05-2008, 06:27 PM
I am stumped on this one.

I have a DIV that is fixed in height. I am trying to put an image within it that should be vertically aligned to the middle (so space on top and bottom is equal). This was the easiest thing in the world to do in old tables but i can't figure it out in CSS. I can't get it to work, the image just aligns to the very top of the DIV.

Here is the code:
.erabox { height: 67px; width: 318px; display: block; }
.erabox img { vertical-align: middle; }

<div class="erabox"><img src="images/10to19.png" alt="1910 to 1919" width="229" height="38" /></div>

---------------

I know how to make it align vertically using margins on the image. BUT i have to repeat this div up to 20 times, and each time the image inside of it will be different sizes because the graphic will be different.

Help! :confused:
HELP!

the_pm
03-05-2008, 06:53 PM
If the graphic has no intrinsic value as part of the content, you could always set it as a non-repeating background, and pad the box to accommodate it :)

Vertical-align aligns inline objects relative to each other, as opposed to being relative to the box. So this won't help with alignment.

Let me play with this and see if I can concoct something :)

Jay August
03-05-2008, 08:10 PM
//EDIT

Read amygdela, read. I bet PHP and getimagesize() is your best bet to get the heights of the images, or use a table.

the_pm
03-05-2008, 08:23 PM
You're going to love this :D

I coded this up as a joke, but now that I look at it, what the hell - it works! If a visitor has JS disabled, no big deal, the object just aligns to the top. Those very few visitors will hardly know the difference - it's not like they're being denied access to content.

Uncomment the alert line in the JavaScript, if you want to see it run one div at a time. Oh, I set both a top and bottom margin to prevent text from wrapping under the image.

http://ex.paulhirsch.com/vertically-align-image/
http://ex.paulhirsch.com/vertically-align-image/shebang.zip - all the files

Enjoy!

DavetheWave
03-05-2008, 08:45 PM
YOU RULE!!! THANKS DUDE :)