tags:

views:

504

answers:

5

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.

Thanks!!

+5  A: 

HTML:

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

CSS:

#something {
    position: absolute;
    height: 200px;
    width: 400px;
    margin: -100px 0 0 -200px;
    top: 50%;
    left: 50%;
}
J-P
Thanks! It works for me!
Why a negative margin here? Thanks!
Because it offsets the size of the div. top and left set to 50% would make the top and left of the element at the middle of the page, not the element itself. The negative margins are exactly half the size of the element and make up the difference so the element itself is centered, not just its top and left sides.
tj111
Ew. Why would you need to position absolutely? Use the damn box model the way it was designed.
Samir Talwar
@Samir: I suggest you try to center a box vertically in a containing block that may grow in height, and then revisit your comment. It is not as easy as it sounds, as vertical positioning and height is one of the greatest shortcomings of the current CSS box model. Its part of the reason so much of sites like ALA are devoted to solving "vertical" problems that CSS doesn't adequately address.
jrista
A: 
margin: auto;
Rony
+3  A: 

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.

jrista
A: 

You can also set your div with the following:

#something {width: 400px; margin: auto;}

With that setting, the div will have a set with, and the margin and either side will automatically set depending on the with of the browser.

Chris
A: 
<html>
<head>
<style>
*
{
    margin:0;
    padding:0;
}

html, body
{
    height:100%;
}

#distance
{
    width:1px;
    height:50%;
    margin-bottom:-300px;
    float:left;
}


#something
{
    position:relative;
    margin:0 auto;
    text-align:left;
    clear:left;
    width:800px;
    min-height:600px;
    height:auto;
    border: solid 1px #993333;
    z-index: 0;
}

/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>

</head>
<body>

<div id="distance"></div>

<div id="something">
</div>
</body>

</html>

Tested in FF2-3, IE6-7, Opera

Rado