Code Reference

Box Model Basics

CSS · Reference cheat sheet

Box Model Basics

CSS · Reference cheat sheet


📋 Overview

Every element is a box made of content, padding, border, and margin. Layout spacing bugs almost always come from misunderstanding this model. Prefer box-sizing: border-box in modern pages.

🔧 Core concepts

LayerRole
ContentText or children; sized by width / height
PaddingSpace inside the border
BorderLine around the padding
MarginSpace outside the border
content-boxDefault: width = content only
border-boxWidth includes padding + border

Vertical margins can collapse between stacked blocks.

💡 Examples

See the box:

.card {
  width: 200px;
  padding: 16px;
  border: 4px solid #334155;
  margin: 24px;
  background: #f8fafc;
}

border-box (recommended):

*,
*::before,
*::after {
  box-sizing: border-box;
}

.box {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  /* total outer width stays 200px with border-box */
}

Margin vs padding:

.section {
  padding: 1rem; /* space inside, keeps background */
  margin-bottom: 2rem; /* space outside, separates from next block */
  background: #e2e8f0;
}

Inspect in DevTools: select an element and view the box model diagram.

⚠️ Pitfalls

  • With content-box, width: 200px + padding + border grows past 200px.
  • margin: auto horizontal centering needs a defined width on block boxes.
  • Margin collapse can remove expected vertical gaps between siblings.
  • Inline elements ignore width/height differently than block elements.

On this page