10.11.2012

How to Center A Website Using CSS

Back in the day of tables, centering was as easy as creating a center tag and placing it around whatever you wanted. With CSS, centering can be a bit tricky depending on what you are wanting to center.

In this post we are only going to cover the basic centering code used to center your entire website and then we'll touch base on some problems you may run into.

Step 1: Start with a container

To begin, create a container (or wrapper, it doesn't matter what you want to call it) in your HTML. This container will box in all of your content. Let me provide you with a visual so that you can see what this container is doing.


Here is the code you'll want to start out with (in between the body tags of the HTML):
<div class="container">
     Header, content, and footer will be placed inside here.
</div>
According to the code, you will place all of your content inside of this container. Because all of your content is within the container, all you have to do to center the content would be to center the container.

Step 2: Set margin's left and right to "auto"

Using CSS, we will use the property "margin" to center our container horizontally on the page.
.container {
     margin: 0 auto;
}
The first attribute that we give to margin is "0". This will give us a top and bottom margin of 0 to our container. The second attribute is "auto". Auto does different things depending on the property it is assigned to. When it is assigned to margin's left and right attribute, it will center it on the page.

Step 3: Give your container a width

However, we are not quite finished. If you leave the CSS at that, nothing will change. The reason is because your container doesn't have a width. If you don't set a width to your container, then your site will automatically have a 100% width and will fill in the entire page. Let's give our container a width.
 .container {
     margin: 0 auto;
     width: 980px;
}
Now our website is centered.

No comments:

Post a Comment