The Box Model

🎨 CSS Layout Lesson 3 Beginner

Every HTML element is a rectangular box. The CSS Box Model defines four layers that control how elements are sized and spaced: content → padding → border → margin.

1 Box Model Layers
  • Content — The actual text or child elements. Controlled by width and height.
  • Padding — Space between content and the border (inside the element). Inherits background color.
  • Border — A visible line around the padding area.
  • Margin — Transparent space outside the border, pushing other elements away.
2 Box Model in Code
CSS — Box Model Properties
.card {
  /* Content area */
  width: 320px;
  height: 200px;

  /* Padding — inside spacing */
  padding: 24px;              /* all sides */
  padding: 12px 24px;         /* top/bottom  left/right */
  padding-top: 12px;

  /* Border */
  border: 2px solid #6366f1;
  border-radius: 12px;

  /* Margin — outside spacing */
  margin: 0 auto;             /* center horizontally */
  margin-bottom: 16px;
}
3 box-sizing: border-box

By default, width applies to the content only, meaning padding and border make the element larger than expected. The border-box model includes padding and border inside the declared width — far more intuitive.

CSS — border-box Reset (Recommended)
*, *::before, *::after {
  box-sizing: border-box;  /* include padding & border in width */
}

/* Now a 320px element stays 320px wide, even with padding */
.card {
  width: 320px;
  padding: 24px;  /* does NOT add to total width */
}
4 Code Challenge
Challenge: Create two .box divs, one with box-sizing: content-box (default) and one with box-sizing: border-box. Give both width: 200px and padding: 20px. Measure their rendered widths using DevTools.