🎨 CSS

The Box Model

Lesson 3 of 5 ~6 min

Every HTML element is treated as a rectangular box. The CSS box model describes how that box is sized and spaced — from the innermost content outward through padding, border, and margin.

The four layers

.box {
  padding: 20px;
  border: 2px solid black;
  margin: 16px;
  width: 200px;
}

box-sizing

By default, CSS uses content-box sizing — the width only applies to the content, and padding and border are added on top. Setting box-sizing: border-box includes padding and border in the element's total width, making layout calculations much simpler.

* {
  box-sizing: border-box;
}

.box {
  width: 200px;
  padding: 20px;
  border: 2px solid black;
  /* Total width is still 200px */
}

Try it yourself

Editor
CSS
Output

Try it

Change the padding, border, and margin values to see how each layer affects the overall box size and spacing.

Quiz

What does box-sizing: border-box do?
Challenge

In the editor above, create a box with 20px padding, a 2px border, and 16px margin. Observe how all three layers work together.