The CSS Box Model Explained

What the Box Model Is

Every element on a web page is rendered as a rectangular box, and the CSS box model describes what that box is made of. From the inside out, a box has four layers: content, padding, border and margin.

LayerWhat it controls
ContentThe actual text or child elements, sized by width and height
PaddingSpace between the content and the border - part of the element's own background
BorderA visible (or invisible) line that wraps the padding and content
MarginSpace outside the border, separating this box from its neighbors - always transparent

Visualizing the Layers

.card {
  width: 200px;
  padding: 16px;
  border: 2px solid #cccccc;
  margin: 24px;
}

Here, the content area is 200px wide, but the box takes up more visual space once padding and border are added - unless box-sizing changes how that width is measured (covered in the Content-box vs Border-box note in this same section).

Margin vs Padding: A Quick Way to Remember

  • Padding is "inside the paint" - it shares the element's background color.
  • Margin is "outside the paint" - it is always see-through and used to space elements apart.
  • Margin between two boxes can collapse into a single gap in some cases (see Margin Collapsing in this section); padding never collapses.

Why the Box Model Matters

Almost every layout bug - text touching the edge of a container, boxes overlapping unexpectedly, elements being wider than their parent - traces back to a misunderstanding of the box model. Learning to picture these four layers makes debugging spacing issues far faster.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.