devnotes.

Understanding the Box Model

Every single HTML element is rendered as a rectangular box, made up of four layers, from the inside out: content, padding, border, and margin.

.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #333;
  margin: 16px;
}
  • Content — the actual text or image, sized by width/height.
  • Padding — transparent space inside the border, between the content and the border (background color/image extends into this area).
  • Border — a visible (or invisible) line surrounding the padding.
  • Margin — transparent space outside the border, separating this box from neighboring elements. Margin never has a background — it's pure empty space.

By default, width: 300px only sets the content width — padding and border are added on top of it, so the box above actually renders 300 + 20+20 (padding) + 2+2 (border) = 344px wide total. This default behavior is called content-box, and it's a very common source of confusion and layout bugs for beginners.

The fix nearly every project uses:

* {
  box-sizing: border-box;
}

With border-box, width: 300px includes padding and border within that 300px, making sizing far more predictable. This single rule is one of the most common lines in any real-world stylesheet.