Alex Rivera | Logout

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

Asked 2009-06-24T19:47:13.007
39

How to put a div in center of browser both vertically and horizontally using CSS only?

Make sure it works on IE7 too.

If everything fails, we may use JavaScript, but a last choice.

Edit
Report

1 Answer

26

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.

answered 2009-06-24T20:01:03.090

Your Answer