HTML and CSS

Centered Designs

An extremely popular layout technique is to center a fixed design along the horizon. This means that the design will always be centered, and whitespace will flow evenly to the right and the left (see Figure 13-8).

Figure 13-8. Fixed, centered layout.

Accomplishing this is somewhat challenging because of the way that elements are centered horizontally in CSS. A number of centering options exist. I'm going to use what's known as the negative-margin approach to horizontal centering. Although it's not the preferred method according to CSS best practices, it is the most supported across browsers (see Example 13-5).

Example 13-5. A fixed, centered design
<style type="text/css">
#container {position: absolute; left: 50%; width: 400px; margin-left: -200px; border: 1px
 solid orange;}
#content {margin-top: 75px;}
#nav {position: fixed; top: 0; width: 400px; border-top: 1px solid orange; border-bottom:
 1px solid orange;}
</style>

To accomplish the layout, you first create a container div, which will then be absolutely positioned. The content, navigation, and any other design components within the centered portion of the design are placed into the container. The negative margin moves the container right into the middle of positioning offset. Figure 13-9 shows the results. I also added a fixed navigation and some additional styles for fun.

Figure 13-9. Fixed, centered designan extremely popular layout.

If you'd like to create a design that is centered but has fluid flow within the content, you can do so by switching to percentage values (see Example 13-6).

Example 13-6. A fluid, centered design
#container {position: absolute; left: 50%; margin-left: -200px; border: 1px solid orange;}
#content {margin-top: 75px;}
#nav {position: fixed; top: 0; border-top: 1px solid orange; border-bottom: 1px solid orange;}