centering diagram

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.

In 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”:
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;
<strong>text-align: left;</strong>
}

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.

Other: 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.



Gửi ý kiến của bạn




Turn off Vietnamese Keyboard


Kiểu gõ:   TELEX  |   Đổi sang VNI   hay   Tắt bộ gõ tiếng Việt

Thông tin bổ xung

  • Dấu * là những thông tin bắt buộc
  • Bạn có thể sử dụng các thẻ HTML sau: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> .
  • Các thẻ cách dòng như <br> và <p> sẽ được tự động tạo ra khi viết.
  • Hỗ trợ hình biểu cảm của Yahoo Messenger.
  • Phản hồi không thích hợp sẽ bị xóa.
  • Nếu đây là lần đầu tiên bạn gửi phản hồi tại đây thì phản hồi của bạn sẽ không xuất hiện ngay sau khi gửi (nhằm chống spam). Điều này cũng sẽ xảy ra nếu bạn sử dụng địa chỉ email mới để gửi. Bạn nên chờ một vài giờ sau để tớ có thể duyệt qua nội dung trước khi chấp nhận, tớ rất lấy làm tiếc về sự bất tiện này.