Centering a Page

As a strategy for controlling the width of a page while allowing for varying monitor resolutions, it is common for web designers to create fixed-width pages that are then centered in the width of the browser window. In the past, this was achieved by slapping a center tag (or <div align="center">...</div>) around a table. In this section, we’ll look at three CSS methods for centering a fixed-width page: the official CSS way, a way that works in Internet Explorer, and an effective “hack.” All three examples have the effect shown in Figure 24-1.

Centering a fixed-width page element

Figure 24-1. Centering a fixed-width page element

In CSS, the proper way to center a fixed-width element is to specify a width for the element that contains all the page’s contents (a div is the usual choice), and then set the left and right margins to auto. According to the CSS visual formatting model, this will have the net effect of centering the element in the initial containing block.

   div#page {width: 500px;
      margin-left: auto;
      margin-right: auto; }

This method works for all current standards-compliant browsers, including Internet Explorer 6 for Windows when it is in “Standards” mode (see Chapter 2 about triggering standards-compliance mode in browsers using the DOCTYPE declaration). It will not work with in IE 6/Windows in “Quirks” mode or any earlier version.

An alternative, yet inelegant, solution is to center the whole page ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.