Make better Web pages by understanding the CSS box model

Components of the CSS box model

This gallery is also available as a TechRepublic article and download, which also includes Listings A-E in a more manageable text file format.

Cascading Style Sheets (CSS) have gradually become the de facto standard for HTML layout and positioning. They're easy to use, don't require any special software, and work uniformly on most major browsers. However, in their very simplicity lies a danger: many novice Web developers use CSS positioning and layout directives without a sound understanding of how they really work. When these directives end up producing unexpected results, such novice developers tend to solve the problem through trial and error, rather than an analysis of fundamentals; this usually creates layout that works well on some browsers but "breaks" on others.

To mitigate this problem, it is worth spending some time to understand some of the core CSS drivers and concepts. And one of the most important concepts a developer can understand is the so-called CSS "box model", which underpins most of CSS layout and positioning. This article provides a brief introduction to this box model, explaining what it is and how you can use it to make better decisions about positioning your HTML elements on a Web page.

The CSS box model represents every element on a Web page in a bounded box which contains four components:

  • the element content itself at the core;
  • an envelope of padding around the element;
  • a border around the padding, which demarcates the visible area of the element;
  • a margin around the border.
When considering how much space an element takes up on a page, the width and height of the content itself are not sufficient. Rather, one must also consider the width and height of the element's padding, borders and margins. This fact, though obvious on reflection, is one that most novice developers are unaware of and is, in fact, the reason behind many instances of overlapping page elements or elements that do not resize correctly with the rest of the page.