CSS - Box Sizing

Overview

Estimated time: 8–10 minutes

Box sizing controls whether width/height includes padding and borders. Understanding this prevents sizing surprises.

Learning Objectives

  • Explain the difference between content-box and border-box.
  • Apply the universal border-box reset responsibly.

Details & Examples

box-sizing: border-box; makes width/height include padding and border—generally easier to reason about.

/* Universal reset - commonly used */
*, *::before, *::after { 
  box-sizing: border-box; 
}

.box-content { 
  box-sizing: content-box; /* default */
  width: 200px; 
  padding: 20px; 
  /* Total width: 240px (200 + 20 + 20) */
}

.box-border { 
  box-sizing: border-box;
  width: 200px; 
  padding: 20px; 
  /* Total width: 200px (padding included) */
}

Common Pitfalls

  • Mixing box-sizing models in the same layout can cause confusion.
  • Third-party components might assume content-box.

Checks for Understanding

  1. What is the total width of an element with width: 100px; padding: 10px; border: 2px solid; using content-box?
  2. What about with border-box?
Show answers
  1. 124px (100 + 10 + 10 + 2 + 2)
  2. 100px (padding and border are included in the width)

Exercises

  1. Create two boxes, one with content-box and one with border-box, both set to width: 200px; padding: 20px;. Verify the visual width difference.
  2. Add a universal border-box reset and explain how it simplifies layout calculations.
Suggested answers
  1. The content-box total width is 240px; border-box remains 200px since padding is included.
  2. *,*::before,*::after{ box-sizing:border-box } makes element width include padding/border, easing responsive sizing.