One good technique for centering a fixed-with CSS layout is to use nested layers, a.k.a. nested divs. A nested layer is a div element inside another div, just as nested tables are tables within tables. In this scenario, the main div is a container. This is the div that you actually center. The nested layers inside provide the site content. Figure 16.1 shows a typical CSS layout with nested layers. Figure 16.1. To build a centered CSS layout, use a container div to hold nested content divs, and then center the container.
This layout calls for four nested divs:
You also need a container div to hold these four. The trick with this technique is to set the left margin of the page to the center point of the browser window, which you achieve by adding the style attribute to the body tag of the page: <body style="margin-left: 50%;"> Notice the percentage value instead of an absolute, pixel-based measurement. Using a percentage here is wise, since you don't know for sure the width of your visitor's browser window. Now, because the left margin of the page begins in the middle of the browser window, you need to express the position of the container div in relation to that margin. Use this code: <div style="position: relative; width: 760px; left: -380px;"> The left offset is a negative number here, and for good reason. Since the position of the container div is relative instead of absolute, the browser uses the left offset a little differently, subtracting 380 pixels from the position of the left margin. Why 380 pixels? Because 380 is half of 760, which is the width of the entire layout. What you're doing, in essence, is finding the center of the page and then moving half of the layout to one side. The result is a perfectly centered container div. When you use this technique, the left offset of the container div is always one-half of its width. However, if you have no time for math, Table 16.1 provides a quick reference.
The nested divs look just like the divs from Topic 15. Their position is absolute, but, because they are nested, the browser uses their parent elementin this case the container divas the reference point for counting top and left offsets, not the upper-left corner of the browser window. Here's the code for the entire layout:
|