Understand the box model

How the box model works

The CSS1 box model provides three different things that can add space around an element: margin, border, and padding. The three serve different purposes. However, the distinction between margin and padding is poorly understood. In a world where no one stylesheet author has total control, the distinction is very important. The key differences are as follows:

Margin
Margin is extra space added outside of the border of an element. The margin has the color of the element's surroundings, since the background is only drawn inside the border. The complete rules for handling margins are somewhat complicated, since they collapse on block level elements.
Padding
Padding is extra space between the content of an element and its border. The padding is filled by the background of the element.

If an element does not have background or border, then it doesn't matter (except for margin collapsing) whether space is given by margin or padding. However, since another stylesheet written by someone else can specify background or border, the choice between margin or padding should be made as though there is a background or border. I think it is generally better to act as though there is a background, and worry less about borders. Borders can be confusing because thinking about borders might make one want both margin and padding and also because borders often require extra space (often padding), whereas backgrounds do not.

For example, should the space to the left of an unnumbered list be given as margin or padding, and on what element, the ul or li? Since the marker-offset gives the offset of the markers from the border edge of the list item, it can't be padding on the li. If a background or border is drawn on the ul element, then one would want the background and border to enclose the bullets. This means the space can't be a margin on a ul (which is unfortunately the traditional interpretation of this space). It should be either a margin on the li or padding on the ul. I happen to prefer (for almost no reason) padding on the ul.

For typical block level elements, usually it is best to specify margin. Padding should usually be specified along with border, although it also makes sense for floating elements or other somewhat separated sections.

One final (somewhat obscure) note: Most of the discussion above has centered on box properties on block-level elements. The box properties all still apply to inline elements, but the top and bottom box properties on non-replaced inline elements do not cause any increase in line spacing (and thus top and bottom margins are useless).

Using the box model

To be written. (One reason it isn't written is that I'm not sure what it will say. Should it lean more towards my notes on related properties or on relying on inheritance?)


Valid HTML 4.0!

(Up to User Stylesheets Guide, CSS, David Baron)

LDB, dbaron@dbaron.org, 1999-08-11