tags:

views:

167

answers:

4

I come up against this challenge frequently -- and when trying to solve I always wonder if I'm doing it wrong.

In a 'div', I want to position an image to the left -- and some corresponding text to the right -- I'd like them to appear vertically centered. What's the best way to do this?

Currently my xhtml looks like this:

<div class="key">
 <img alt="required" src="/images/forms/asterisk.png?" /> required
</div>

Here's how it currently looks -- http://screencast.com/t/NGMxMjRmMmYt (you'll see that the asterisk image is not vertically aligned with the "required" text. Boooo.

I typically think about positioning the image absolutely and then adding some left padding to move the text over, then later adjusting the top and bottom padding to get the text vertically centered. In the end, this approach seems like way too much work.

A: 

If the container DIV and Image both have fixed width and height then you could use CSS, but if not, jQuery Center Plugin is by far the best solution.

Nimbuz
A: 

There are a number of options (see Vertical Centering with CSS for the complete rundown). Which one is best depends on a number of factors, the biggest being whether you know the dimensions of your content or not.

If you're just wanting to center the text in relation to the image, setting the text's line-height to the height of the image/container may be the easiest approach...

bdukes
`line-height` does not work consistently among browser engines for vertically centering. I usually get text that is a pixel too low in Webkit and several pixels too high in Gecko. So I opt for explicit heights with a relative position (50%) and negative top margin (half the height), usually on the text's parent anchor. If it's anchor-less a span is then required, sadly.
jonwd7
+1  A: 

Adding this to your style should do it:

.key * {
   vertical-align: middle;
}

You're basically saying "every element inside the key class element needs to be vertically centered". This is the markup I follow (usually a .button class) and works in IE, Chrome, FF, Safari.

Parrots
A: 

The following CSS will work:

.key img {
    vertical-align: middle;
}

Hope this helps! :-)

The Elite Gentleman
All images inside the key class will be vertically aligned.
The Elite Gentleman