trovster.com

The personal website of Trevor Morris

Centering Block Elements

A common practice which is often desired in web design is centering the entire website - which can be achieved fairly easily. If you wish to center block elements, such as containers <div>, lists or even paragraphs, all you need is to define a width and margin.

#container {
  margin: 0 auto;
  width: 760px;
}

This will center an element with the id of #container, which is usually used as a wrapper of the entire site. However, this will need some additions if you wish to support older browsers, such as IE5mac or IE5win.

Because IE5 (including 5.5) uses its quirks rendering engine, it handles centering block elements as you would 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 will 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;
}