CSS Box Model & Layout

Difficulty: Beginner

Question

Explain the CSS box model. What is the difference between content-box and border-box?

Answer

Every element is a rectangular box with: - Content: the actual content area - Padding: space between content and border - Border: the border around padding - Margin: space outside the border

box-sizing: content-box (default) - width/height only applies to content. Padding and border are added on top. box-sizing: border-box - width/height includes content + padding + border. Much more predictable.

Margin collapsing: adjacent vertical margins collapse into the larger value, not additive.

Code examples

content-box vs border-box

/* content-box (default) */
.element {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  /* Actual rendered width: 200 + 40 + 10 = 250px */
}

/* border-box (recommended) */
.element {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  /* Actual rendered width: 200px */
  /* Content area: 200 - 40 - 10 = 150px */
}

/* Global reset (best practice) */
*, *::before, *::after {
  box-sizing: border-box;
}

border-box makes sizing predictable. Always apply the global reset so every element uses border-box.

Margin Collapsing

/* Vertical margins collapse */
.box-a { margin-bottom: 20px; }
.box-b { margin-top: 30px; }
/* Gap between A and B = 30px (not 50px) */

/* Margins do NOT collapse when: */
/* 1. Horizontal margins */
.inline { margin-left: 10px; margin-right: 10px; }

/* 2. Parent has padding or border */
.parent {
  padding: 1px; /* prevents child margin from collapsing */
}

/* 3. Flex/Grid containers */
.flex-parent {
  display: flex;
  flex-direction: column;
  /* Child margins do NOT collapse here */
}

Margin collapsing only happens vertically between block elements. Flex and grid containers prevent it entirely.

Visualizing the Box Model

<!-- Open DevTools > Elements > Computed tab
     to see the box model diagram -->

<div class="box">Content</div>

<style>
.box {
  /* Content */
  width: 300px;
  height: 100px;

  /* Padding (inside border) */
  padding: 16px 24px;

  /* Border */
  border: 2px solid #333;

  /* Margin (outside border) */
  margin: 20px auto; /* 20px top/bottom, centered */

  /* With border-box, total width = 300px */
  box-sizing: border-box;
}
</style>

Use Chrome DevTools Computed tab to visualize the box model of any element. Hover over the diagram to highlight each layer on the page.

Key points

Concepts covered

Box Model, content-box, border-box, Margin Collapsing, Layout