views:

4426

answers:

3

I want to center a div vertically with CSS. I don't want tables or Javascript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.

<body>
    <div>Div to be aligned vertically</div>
</body>

How can I center a div vertically in all major browsers, including Internet Explorer 6?

+5  A: 

You can read up on this little article on vertical centering with div tags.

Vertical Centering in CSS

Ólafur Waage
Very interesting article!
Gamecat
Burak said no tables. Or are you saying that table specified in HTML is bad, but specified in CSS is OK?
buti-oxa
great article. I would surely use this method very soon. Thanks!
Ionut Staicu
"table specified in HTML is bad, but specified in CSS is OK?"Yes. HTML is the basic markup of the content, and it should be semantically correct for the content. CSS is purely for visual layout and eye candy, for which "table" or other paradigms are fine if that's what you want.
mattandrews
Doesn't work in Safari on Mac OSX
James
@James this is a very old question and an old answer. Vertical centering is almost always a trick to get working in all browsers and all versions.
Ólafur Waage
+8  A: 

Actually you need two div's for vertical centering. The div containing the content must have a width and height.

<body>
<div id="container">
  <div id="content">
    <h1>Centered div</h1>
  </div>
</div>
</body>

#container{
   position: absolute;
   top: 50%;
   margin-top: -200px;/* half of #content height*/
   left: 0;
   width: 100%;
}
#content {
   width: 624px;
   margin-left: auto;
   margin-right: auto;
   height: 395px;
}
+5  A: 

Unfortunately — but not surprisingly — the solution is more complicated than one would wish it to be. Also unfortunately, you'll need to use additional divs around the div you want vertically centered.

For standards-compliant browsers like Mozilla, Opera, Safari, etc. you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%. The following pages explain this technique well and provide some code samples too:

There is also a technique to do the vertical centering using Javascript. Vertical alignment of content with JavaScript & CSS demonstrates it.