How to Center A Website

The tip for today is how to center a website using CSS.  This is very problematic for many individuals new to doing web design.  Heck, I ran into a website that simply wouldn’t center when I was designing it today!

Why would you want to center the content on your website?  Well, for starters – how many people have large monitors or monitors with large screen resolutions?  Now, how many people still are running in 800 x 600 mode?  Quite a few.  So, those individuals that have high screen resolutions – you don’t want the content of your website to be static using margin CSS attributes.  You want it to “float” to the center all the time.  Unfortunately, there is not a “center” float in CSS (there is a left and right).  So you have to design your website to use other margin attributes so that it is always centered for anyone with any size screen resolution.

The first thing you need to do is declare some items in your CSS file.  Typically you will have a website that is setup with the following tags:

<html>
<head>
….
</head>
<body id=”site”>
<div id=”container”>
…… put your stuff here
</div>
</body>
</html>

So, in your CSS file, you want to have the main body of the website centered.  You can apply it to either “site” or to the “container” dividers as they are listed above.

A BIG note – No matter how much you try to use the below CSS attributes, they will not work unless you have this at the very top – or the very first line in your HTML document:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

I ran into this problem today actually.  When I designed the website, I had the CSS below setup properly – but for the life of me, I couldn’t figure out why the content was not centered in the middle of the page.  The page was centered and looked perfect in Firefox, but it simply looked like crap and was all to the left in Internet Explorer.

Now, here is the CSS code that you’ll put in your stylesheet.  I am basing this off of using the “container” divider as indicated above; I’m not setting it using the “site” ID for the body tag.

margin-left: auto;
margin-right: auto;

You can also simply use this code as well, and it does the same thing:

margin: 0px auto;

So, two ways of doing it, but ensure that you add the line above at the top of your web page.