How to put a div in center of browser using CSS?

HTML:

<div id="something">... content ...</div>

CSS:

#something {
    position: absolute;
    height: 200px;
    width: 400px;
    margin: -100px 0 0 -200px;
    top: 50%;
    left: 50%;
}

margin: auto;

The simplest solution is just to use an auto margin, and give your div a fixed width and height. This will work in IE7, FF, Opera, Safari, and Chrome:

HTML:

<body>
  <div class="centered">...</div>
</body>

CSS:

body { width: 100%; height: 100%; margin: 0px; padding: 0px; }

.centered
{
    margin: auto;
    width: 400px;
    height: 200px;
}

EDIT!! Sorry, I just noticed you said vertically...the default "auto" margin for top and bottom is zero...so this will only center it horizontally. The only solution to position vertically and horizontally is to muck around with negative margins like the accepted answer.

Tags:

Css

Layout