Center a Page Vertically and Horizontally in HTML
To center a page vertically and horizontally in HTML is fairly simple. The method below works in all Windows browsers and I believe all Apple browsers, but it has trouble working in Linux browsers from what I’ve seen (I’ve seen it not work for the vertical alignment, only for horizontal, but this could have changed since).
Essentially all you do is:
- Position your container div absolutely.
- Place the top and left positions as 50%.
- Set a height and width (since this is also for centering vertically).
- Set the top and left margins to a negative number that is half the height and width you set. So if your width is 300 pixels, you’d set your margin-left to -150 pixels. If your height is 400 pixels, then set your margin-top to -200 pixels.
Sample:
.wrapper_container {
position: absolute;
top: 50%;
left: 50%;
width: 900px;
height: 545px;
margin-left: -450px; /*set to a negative number 1/2 of your width*/
margin-top: -272px; /*set to a negative number 1/2 of your height*/
background: url("/images/ui/splash.jpg") top left no-repeat;
display: block;
}
Naturally most people just want to center horizontally, in which case everyone just sets the body tag to text-align center (for IE), and then the container div to margin: 0 auto; (for FF). This is fairly common practice, I’m just including it here for posterity.
Sample:
body {
text-align: center;
}
.wrapper_container {
width: 980px;
margin: 0 auto;
}