Bite Size Standards offers concise web development tutorials, tips, and tricks written by designers and developers who are passionate about web standards. More about us
A common practice in web design is centering the entire web page in relation to the viewport. If you wish to center block elements such as divs, lists or even paragraphs, all you need to do is to define a width and margin.
#container {
margin: 0 auto;
width: 760px;
}
The code above will center an HTML element with the id of #container (which is a common name used for the div “wrapper” of an entire page). This will, however, need some additions if you wish to support older browsers such as Internet Explorer 5.
Because IE5 (including 5.5) is stuck permanently in quirks mode, it handles block elements in the same way as inline elements.
This means you need to add text-align: center; to the container, which in this case is the body element.
Internet Explorer 5 on the Macintosh (discontinued) needs the entire shorthand definition to center the container. This leaves us with the following code:
body {
text-align: center; /* for IE5 and IE5.5 on Windows */
}
#container {
text-align: left; /* combat the alignment on the body */
margin: 0 auto 0 auto; /* for IE5mac */
width: 760px;
}
Commenting is closed for this article.
TJSingleton
: http://tj.preachersweb.org
27 May 2006, 05:43 : Permanent link to comment
You can also use the body as the “container” and set a body width with the margin set to “0 auto”. This will save you from an extra div.
For Instance,
@ body {
width: 760px;
margin: 0 auto; } @
But, this won’t work with ie 5.x, I don’t think you can resize it’s body.
Dustin Diaz brought this to my attention.
Justin Perkins
: http://www.iamjp.com
27 May 2006, 06:58 : Permanent link to comment
Vertical centering anyone?
Jens Meiert
: http://meiert.com/
28 May 2006, 01:50 : Permanent link to comment
“margin: auto;” suffices (compared to those “0 auto” and “0 auto 0 auto” values). No need to jump on IE Mac, right.
Filosof
: http://blog.filosof.biz/
29 May 2006, 22:49 : Permanent link to comment
Vertical centering – Yuh?’s solution
Karl
: http://www.thatstandardsguy.co.uk
29 May 2006, 23:44 : Permanent link to comment
Ahh, thanks for the IE5 Mac tip there – some of us (local gov) still have to support that browser.
Erik
: http://erikanderica.org/erik/
31 May 2006, 04:38 : Permanent link to comment
@Justin—Bert Bos has additional advice on vertical centering