Home Module 04 The Box Model

1. Introduction

The CSS Box Model is arguably the most important concept in CSS. Every single HTML element — whether a <div>, a <p>, a <button>, or even an image — is treated as a rectangular box by the browser.

Understanding the box model explains:

  • Why adding padding makes an element bigger than you expect
  • Why two elements are colliding or overlapping
  • How to control spacing between elements
  • Why elements don't line up the way you intended

Once you understand the box model, a lot of confusing CSS behaviour suddenly makes complete sense.

2. Theory

The Four Layers

Every element's box consists of four layers, from inside to outside:

  1. Content — where the text or images actually appear. Controlled by width and height.
  2. Padding — the space inside the element, between the content and the border. Controlled by padding.
  3. Border — the line around the element, between padding and margin. Controlled by border.
  4. Margin — the space outside the element, between this element and others. Controlled by margin.
/* Visual representation */
┌─────────────────────────────┐  ← margin (transparent)
│  ┌───────────────────────┐  │  ← border
│  │  ┌─────────────────┐  │  │  ← padding
│  │  │    content      │  │  │
│  │  └─────────────────┘  │  │
│  └───────────────────────┘  │
└─────────────────────────────┘

Width and Height

.box {
  width: 300px;
  height: 200px;
}

Padding

Padding creates space inside the element. It has the element's background colour.

/* Individual sides */
padding-top: 16px;
padding-right: 24px;
padding-bottom: 16px;
padding-left: 24px;

/* Shorthand: top right bottom left (clockwise) */
padding: 16px 24px 16px 24px;

/* Shorthand: top/bottom  left/right */
padding: 16px 24px;

/* All sides equal */
padding: 16px;

Border

/* Individual properties */
border-width: 2px;
border-style: solid;  /* solid, dashed, dotted, double, none */
border-color: #2563eb;

/* Shorthand */
border: 2px solid #2563eb;

/* Individual sides */
border-top: 3px solid #f59e0b;
border-left: none;

/* Radius — rounds corners */
border-radius: 8px;          /* all corners */
border-radius: 50%;           /* makes a circle (if width = height) */
border-radius: 4px 8px 4px 8px; /* top-left top-right bottom-right bottom-left */

Margin

Margin creates space outside the element. It is always transparent — shows the parent's background.

/* Same shorthand as padding */
margin: 16px;
margin: 16px 24px;
margin: 16px 24px 32px 24px;

/* Auto — centre an element horizontally */
margin: 0 auto;

/* Negative margins */
margin-top: -8px; /* pulls element up (use sparingly) */

box-sizing: The Critical Property

By default, width and height only set the content area. Padding and border are added on top, making the element bigger than you specified. This is called content-box.

/* Default (content-box): total width = 300 + 20 + 20 + 2 + 2 = 344px */
.box {
  box-sizing: content-box; /* default */
  width: 300px;
  padding: 20px;
  border: 2px solid black;
}

Switching to border-box includes padding and border inside the specified width — the total width stays exactly 300px:

/* border-box: total width stays exactly 300px */
.box {
  box-sizing: border-box; /* MUCH more intuitive */
  width: 300px;
  padding: 20px;
  border: 2px solid black;
  /* content area = 300 - 20 - 20 - 2 - 2 = 256px */
}

Almost every professional CSS stylesheet uses this at the top to apply border-box to everything:

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

Margin Collapse

When two vertical margins touch, they collapse into a single margin equal to the larger of the two. This is a common source of confusion.

h2 { margin-bottom: 32px; }
p  { margin-top: 16px; }

/* Between h2 and p, the gap is 32px (not 32+16=48px) */
/* The margins collapse to the larger value */

Margin collapse only happens vertically (top/bottom), not horizontally (left/right).

Outline vs Border

outline is similar to border but does NOT take up space — it does not affect layout. Used for focus indicators.

button:focus {
  outline: 3px solid #f59e0b;
  outline-offset: 2px; /* gap between element and outline */
}

3. Real World Example

When you click on a button and it has visible spacing around the text, that is padding. When two buttons next to each other have a gap between them, that is margin. When a card has a visible border line, that is the border property.

The most common debugging scenario: "My div is wider than I expected". This is almost always a box-sizing issue — the padding is being added to the width. The fix: box-sizing: border-box.

4. Code Example

/* Apply border-box globally — always do this first */
*, *::before, *::after {
  box-sizing: border-box;
}

/* Card component */
.card {
  width: 100%;           /* fills parent width */
  max-width: 400px;
  padding: 24px;         /* space inside the card */
  border: 1px solid #e2e8f0; /* border around card */
  border-radius: 12px;   /* rounded corners */
  margin-bottom: 24px;   /* space below each card */
  background-color: white;
}

.card-header {
  padding-bottom: 16px;
  border-bottom: 1px solid #f1f5f9;
  margin-bottom: 16px;
}

.card h2 {
  margin: 0 0 8px 0; /* top right bottom left */
  font-size: 1.25rem;
}

.card p {
  margin: 0;
  color: #64748b;
  line-height: 1.6;
}

/* Button */
.btn {
  display: inline-block;
  padding: 10px 20px;      /* vertical horizontal */
  border: none;
  border-radius: 6px;
  margin-top: 16px;
  cursor: pointer;
  font-size: 0.875rem;
  font-weight: 600;
}

.btn-primary {
  background-color: #2563eb;
  color: white;
}

.btn-primary:hover {
  background-color: #1d4ed8;
}

/* Debugging — temporarily add to see element boxes */
/* .debug * { outline: 1px solid red; } */

5. Code Breakdown

*, *::before, *::after { box-sizing: border-box; }
This is the single most important reset to add. It changes the box model for every element so padding and border are included inside the width — making sizing far more intuitive. Always put this at the very top of your CSS.
max-width: 400px
The card uses width: 100% so it fills its container, but max-width: 400px prevents it from getting too wide. On mobile it fills the screen; on desktop it caps at 400px.
margin: 0 0 8px 0
Explicitly setting all four margin values to reset browser defaults while adding only bottom margin. Without this, the browser's default heading margins would add unintended spacing.
display: inline-block on .btn
Links (<a>) are inline by default and cannot have meaningful width/height/padding. inline-block lets them behave like a block (accept padding) while staying in the text flow.
/* .debug * { outline: 1px solid red; } */
A commented-out debug trick. Uncomment it when confused about why elements have unexpected sizes — it draws a red outline around every element showing their exact boundaries without affecting layout.

6. Common Mistakes

  • Not setting box-sizing: border-box. This is the single biggest source of layout confusion for beginners. Always add it to the reset.
  • Confusing padding and margin. Padding is INSIDE the element (has the background colour). Margin is OUTSIDE (always transparent). Use padding for internal spacing, margin for spacing between elements.
  • Not expecting margin collapse. Two paragraphs with margin: 16px each will have a 16px gap between them (not 32px) because vertical margins collapse.
  • Using width: 100% with padding causing overflow. Without border-box, width: 100%; padding: 20px; makes the element 40px wider than its parent. With border-box, it fits perfectly.
  • Removing focus outlines. Many beginners write outline: none or outline: 0 because they find the default focus ring ugly. This destroys keyboard accessibility. Instead, style it nicely.

7. Best Practices

  • Always use box-sizing: border-box — apply it to all elements at the start of every CSS file.
  • Use padding for internal spacing, margin for spacing between elements.
  • Reset margins on headings inside components — browser defaults add margins that break card/component layouts.
  • Use the debug outline trick during development to understand layout issues.
  • Use browser DevTools (F12 → Elements → Computed) to see the box model visually for any element.
  • Style focus outlines attractively — never just remove them.

8. Practice Exercise

  1. Create a box-model.html with three boxes: a small, medium, and large div, each with a visible border, background colour, padding, and margin
  2. Add box-sizing: border-box to all — then remove it. Notice the size difference in the browser
  3. Open browser DevTools (F12), click on an element, and find the "Box Model" diagram in the Computed styles panel. Read the four values
  4. Create two paragraphs with margin-bottom: 32px and margin-top: 32px. Open DevTools and confirm the gap is 32px (collapsed), not 64px
  5. Create a button with hover state: normal state has 10px 20px padding; hover state has 12px 24px padding. Notice how the surrounding content shifts slightly — this is layout reflow

9. Assignment

Build a card component library demonstrating the box model:

  • Three card variants: default, outlined (border but no shadow), and elevated (shadow, no border)
  • Each card has: header area with title + subtitle, body with paragraph text, footer with a button
  • Use box-sizing: border-box globally
  • Use padding for all internal spacing, margin for spacing between cards
  • Show the same card at three widths: 100%, 400px fixed, and 300px — all should look proportional
  • Use DevTools to verify the box model of your cards and note the values in a comment

10. Interview Questions

Q1: Explain the CSS Box Model.

Answer: Every HTML element is a rectangular box consisting of four layers: the content area (where text/images go), padding (space inside between content and border), border (the line around the element), and margin (space outside the element separating it from others).

Q2: What is the difference between padding and margin?

Answer: Padding is the space inside an element — it has the element's background colour. Margin is space outside the element — it is always transparent. Padding pushes the border outward; margin pushes other elements away.

Q3: What is box-sizing: border-box and why is it useful?

Answer: By default (content-box), width/height only measure the content area — padding and border are added on top. border-box includes padding and border inside the specified width/height. This makes sizing far more intuitive — a width: 300px element stays exactly 300px wide regardless of padding.

Q4: What is margin collapse?

Answer: When two vertical margins touch (e.g. the bottom margin of one element and top margin of the next), they collapse into a single margin equal to the larger of the two values. For example, a 32px bottom margin and 16px top margin = 32px gap, not 48px. This only happens vertically, not horizontally.

Q5: How do you horizontally centre a block element?

Answer: Give it an explicit width (or max-width) and set margin-left: auto; margin-right: auto; — shorthand: margin: 0 auto;. Auto margins distribute equally on both sides. This does not work for elements without a width constraint.

11. Additional Resources

  • MDN Web Docs — The Box Model (search "MDN CSS box model")
  • CSS-Tricks — The CSS Box Model (search "css-tricks box model")
  • Browser DevTools — F12 → Elements → Computed → Box Model diagram
  • MDN — box-sizing (search "MDN box-sizing")
  • MDN — Mastering margin collapsing (search "MDN margin collapsing")