views:

175

answers:

2

I have a div and an image within the div. The image size will vary.

I want it to be centered horizontally and vertically. Css verticle align does't seem to work.

Any tricks? I can use php, css or Jquery

+2  A: 

You can get it to align horizontally by using

margin: 0 auto;

Centring vertically isn't easy with CSS (at least not in IE6/7). It's relatively easy to do it with tables.

You say you have jQuery available. You can kick any browser into gear by applying JavaScript. But of course without JS enabled/supported, your page will not appear correctly.

CSS's vertical-align property is only meant to be used within something with display: table-cell (which itself should be in something with display: table).

If you had

<div id="container"><img src="my-image.png" alt="" /></div>

You could use jQuery to center it like this (as in the suggestion by plexus)

var imageSrc = $('#container img').attr('src');

$('#container').css({ backgroundImage: 'url(' + imageSrc + ')', backgroundPosition: 'center enter' });
alex
Well its a Jquery intensive site, so I dont mind it looking a little off when javascript is turned off.
Wes
A: 

I don't know how you use it, so probably my solution won't fit.

When you implement the image as a 'background-image' within the div you can easily center it with 'background-position':

#div {
background-image: url(./image.png);
background-position: center center;
}
plexus
Thats a great idea. I need the image to link to something but I may be able to get away with a transparent span and use this suggestion. Will report back :)
Wes