Saturday, March 22, 2008

How to Center a lay-out in CSS

The following is documented in order to provide a neat and tidy way of responding to a frequently asked question here at SimpleBits:

How do I center a fixed-width layout using CSS?

For those that know, it’s simple. For those that don’t, finding the two necessary rules to complete the job can be frustrating. So here it goes.

centering diagramIn the markup, we’ll need a container to hold everything. In this container will sit the entire layout that we’d like to center on the page. We’ll suspiciously name this container: “container”:



...entire layout goes here...

Using CSS, the following two rules force whatever is contained within #container to be centered:

body {
text-align: center;
}

#container {
margin: 0 auto;
width: xxxpx;
}

We’re aligning everything within body to be centered, while giving the #container a specific width (whatever you’d like). The margin: 0 auto; is the second piece which makes it all work. We’re specifying 0 pixels on top and bottom, with auto margins on the left and right.

That’s it. The only problem we’ll run into now is that, because we haven’t specfied otherwise, everything on the page will be centered. We’ll want to override that from the container level down with the addition of the following rule:

#container {
margin: 0 auto;
width: xxxpx;
text-align: left;
}

With that single declaration, everything within #container will be left-aligned, yet leaving our centered layout unhindered. The same principle could be applied not only in centering entire layouts, but other block-level elements and page components.

Now I’ll just need to keep the URL for this entry handy the next time the question is posed, helping me respond to emails that inquire about this seemingly simple goal. And these days, anything that helps me respond to email is a true asset, as I’ve been absolutely terrible at the task lately.

Update: Several people have written in, either to ask why text-align: center; is necessary, or that using that rule is plain wrong. The reason it’s used, is for the benefit of IE5/Win users. Without the rule, most browsers will still center the layout just fine using auto left and right margins — but not IE5/Win.

1 comment:

Dan said...

And that helps. Thanks for providing a clearly-detailed idea and steps on how I could do the thing. Actually I'm using a method to center CSS layout but yours is more modified and works much easy.

computer assistance