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!!
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!!
HTML:
<div id="something">... content ...</div>
CSS:
#something {
position: absolute;
height: 200px;
width: 400px;
margin: -100px 0 0 -200px;
top: 50%;
left: 50%;
}
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.
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.
<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