Do You Want To Do That With CSS? — Centering a Wrapper

By: John Gallant , Holly Bergevin ,

Page 1 of 3

Set for printing


This article will deal with one of the most basic problems encountered when developing a tableless design, namely getting a fixed width "page wrapper" element to center at all window resolutions and in all modern browsers.

What is a "Wrapper?"

For a good explanation of what a wrapper is, please see Working With a Wrapper Div by CMX's own Adrian Senior. We'll go ahead and recap the main points.

Essentially, a wrapper is nothing more than a generic <div> element that usually contains all the other page elements. This wrapper div provides a way to constrain the width of the page content, and can also be colored, bordered, and perhaps even display a background image. In short, a wrapper can be a very useful thing to have.

Such a wrapper can be reliably centered in all browsers by applying identical side margins to the div, spacing it away from the sides of the browser window, technically known as the viewport. The wrapper is centered all right, but there's one problem with this construction. Since the sides of the wrapper are tied to the sides of the viewport by these margins, the width of the wrapper is always related to the width of the viewport. Even if the margins are percentages, this remains true.

<div class="wrapper">contents of page</div>
The CSS:
div.wrapper {
   margin-left: 10%;
   margin-right: 10%;
/* width of div.wrapper is always 80% of viewport width */

Code Block 1

This type of layout is called "liquid" or "fluid," because the main content area adjusts to the viewport width, whatever that width may be. Sometimes this is just what the author wants, but the majority of clients seem to prefer a "rigid" design that is set to a specific pixel width. By setting a specific width, text may be kept to a reasonable number of words per line, at least for typical browser settings. "Rigid" in this case means giving the wrapper a fixed width that matches the smallest common screen resolution. This common resolution used to be 640px, but these days very few users still use that setting. The vast majority now have 800px or 1024px screen widths.

Thus, by making the wrapper about 770px wide, the wrapper will fit into both of the major resolution settings without triggering the dreaded "horizontal scrollbar," assuming the browser window is fully maximized. It's not a good idea to set the wrapper to a wider width, for example 800px, because the browser's vertical scrollbar needs to be accounted for, and the exact amount of needed "wiggle room" varies between browsers. Therefore, a good safe width is about 770px.

Page 1 of 3 1 2 3 Next

Download Support Files

Downloads are disabled during your trial period.

wrapper, centering, CSS, wrapper div, auto margins, margin, margins, centered content, centering content