CSS ยท Chapter 11 of 44

CSS Box Model

Every HTML element is a rectangular box made of content, padding, border, and margin, from innermost to outermost. This is the CSS box model.

Understanding the box model is essential for controlling layout, spacing, and sizing accurately.

Syntax
box-sizing: border-box;

The four layers

Content holds text/images. Padding surrounds content. Border wraps padding. Margin is outside the border, separating from other elements.

box-sizing property

By default (content-box), width/height apply only to content, and padding/border add extra size. box-sizing: border-box includes padding and border within the declared width/height.

Example 1 (css)
* {
  box-sizing: border-box;
}
.box {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
}
Output
A box that is exactly 200px wide total, including padding and border

border-box makes the declared width include padding and border, simplifying layout math.

Key points

  • The box model layers are content, padding, border, and margin.
  • Default box-sizing is content-box.
  • border-box includes padding/border in the width calculation.
  • Applying box-sizing: border-box globally is a common best practice.
๐Ÿ’ก Note: Many CSS resets set box-sizing: border-box on all elements to simplify sizing.

๐Ÿ“ Quick Quiz

1. What are the four layers of the box model, from inside out?

2. What is the default box-sizing value?

3. What does box-sizing: border-box do?