views:

339

answers:

2

So I know all about the problems with vertical-align: middle; and the different methods people have used to vertical align elements in CSS. But I haven't found one that works for what I need it to work for.

Basically my page has just one <div> on it, which I want positioned in the center of the page, both horizontally and vertically. Obviously the horizontal part is easy, but I'm getting hung up on the vertical part. My problem is that the height of the <div> is unknown; the content changes, so I can't specify a height for it.

Anyone have any tips for me? I'm willing to use JavaScript if necessary. Thanks!

+3  A: 

Long story short, you need two divs to get CSS-only vertical centering.

With Javascript, you can do it with a single div, though.

mattandrews
A: 

As you said you don't mind using JS, here it is... (I generally never fallback to a JS solution, but if you're cool with it, then so am I)

If your CSS is

#element {
    position: absolute;
    top: 50%;
}

Then you could use my friend jQuery

$(document).ready(function() {
    var height = $('#element').height();
    $('#element').css({marginTop: '-' + (height / 2) + 'px'})

{);

Note, this is untested, but should be a start. Hopefully the height / 2 will work as expected, if not, try using parseInt();

alex