tags:

views:

304

answers:

2

We have a login page that is designed to have a 200px-high DIV vertically centered in the middle of the page. That is, it creates a 200 pixel blue band left edge to right edge (with form elements in it) that ideally should remain vertically centered in the viewport no matter how the browser window is resized.

This must be a CSS solution.

So let's say here's some sample markup:

<body>
    <div id="mainDiv">
       <div id="centerDiv" style="height:200px;background-color:blue;color:white">
           Center this baby vertically in the #mainDiv, please!
        </div>
    </div>
</body>

Assume that my CSS dictates that the #mainDiv is stretched to cover the viewport top and bottom, which is easy enough to do. Are there CSS rules that I can apply to any of the elements or the page that will reliably and cross-browser (incl. IE6) vertically center #centerDiv? In a perfect world we should just be able to say

#centerDiv {
  margin: auto 0;
}

And even in an OK world we should be able to address this issue with a few styles. But to quote Ving Rhames' character from Pulp Fiction, We're pretty %&#!ing far from OK.

I've looked at the solutions offered in Related Questions and scoured the Web. Nothing I can find really works 100%. Maybe this is unsolvable, but I thought I'd give the collective brains here the problem and see if I can get lucky. Thanks in advance.

+2  A: 

If you have a fixed height, you can do it. Give the child div a top of 50% and a margin-top of -100px (or vice-versa) and you should be set.

Tom
Tom, this works great, thanks. I had actually tried a version of this before without success, but when I saw your answer I went back and looked at that code again and found some cruft, including a stray "margin: auto 0" rule, which ruined the whole thing. Once I removed that, it worked. Thanks much!
Robusto
+1  A: 

For true automatic positioning in the center, the inner DIV would need to know the boundaries of the containing DIV. If your container does not have hard boundaries, there is no way for the inner DIV to calculate its own position automatically. It simply has no frame of reference.

The closest I think you can make it with a simple CSS solution is this:

    #mainDiv
    {

     border: 1px dashed #000000;   
    }

    #centerDiv
    {
        margin: 33% auto;
        height: 200px;          
    }
Rob Allen