tags:

views:

67

answers:

3

How on earth do you center a div vertically?

Horizontal has enough ways already, but no matter what i try, vertical centering is just impossible.

body { vertical-align: middle;}

Does nothing

body {text-align: middle;}

Does nothing

div.middle {top: 50%;}

Does nothing

Is it even possible?

I think i'm gonna cry.

+4  A: 

See Vertical Centering in CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to ser it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>
cletus
thanks, nice code but, there's that damn 'set height' limit again, so i guess there's no way to center a block for use with different screen res?
Brae
You can make the outer div 100% height. See http://stackoverflow.com/questions/25238/100-min-height-css-layout
cletus
A: 

The div has to have a fixed height in order to make it possible, as far as I know.

#centered { width: 700px; height: 400px; position: absolute; top: 50%; left: 50%; margin: -200px 0 0 -350px; }

And make the parent layer of #centered relatively positioned. That should work.

Edit - So it is possible to have an undefined height. See cletus' answer.

JoostK
no, you need defined height
Brae
A: 

This might Help: http://ask.amoeba.co.in/

Aneeska
nice,but i think mine is a little more versetile, even though mine uses javascript.
Brae