How to Center a Website with CSS
The question about centering your website in the visitor’s screen always comes up. Fortunately, the solution is really very simple.
Essentially, you can have two different types of website layouts - fixed and liquid widths. Fixed widths stay, well…fixed. Liquid layouts stretch to suit the size of your visitor’s screen.
How to Center Liquid Layouts
Liquid layouts are very simple to center. Assuming you have a main container div in place, simply set the left and right margins the same, like the following, for example:
div#container {
margin-left: 20%;
margin-right: 20%;
}
How to Center Fixed-width Layouts
Fixed-width layouts work a bit different from liquid layouts. According to the W3C, “If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.”
div#container {
margin-left: auto;
margin-right: auto;
width: 900px;
}
In other words, setting the margin-left and margin-right properties to auto should center your webpage. However, because older versions of IE are so nice to web developers, they ignore auto margins completely. To fix this, centering the body content does the trick nicely.
body {
text-align: center;
}
The problem with this is that now all your page’s content is centered. To fix this, just reset the alignment of the container div.
div#container {
margin-left: auto;
margin-right: auto;
width: 900px;
text-align: left;
}
What about “div#container”?
Now all you have to do is wrap a “container” div around your entire page’s content, like so.
<body>
<div id="container">
<!-- your content goes here -->
</div>
</body>
| Print article | This entry was posted by kpac on March 24, 2010 at 6:49 pm, and is filed under CSS Tutorials. Follow any responses to this post through RSS 2.0. You can skip to the end and leave a response. Pinging is currently not allowed. |

about 4 months ago
Hi there!
Good and informative post.
It’s possible to further improve the centering code with shorthand:
margin: 0 auto;
Cheers
about 10 months ago
thanks for the quick tips on centering the layout
about 1 year ago
Hi There,
Centering a website is a key part of many CSS layouts. While there are many ways to do it in a variety of situations.
Thanks,
Mick