CSS Box Model

Understand how content, padding, borders, and margins determine element size.

Diagram illustrating the content, padding, border, and margin layers of the CSS box model

CSS Box Model

Every HTML element is a box made of four layers:

  1. Content – text, images, or other elements.
  2. Padding – space around the content.
  3. Border – the line surrounding the padding.
  4. Margin – space outside the border.

Example

CSS
.card {
  width: 300px;
  padding: 20px;
  border: 2px solid blue;
  margin: 30px;
}

The background covers the content and padding, but not the margin.

Calculating the Total Size

By default, padding and borders are added to the declared width and height.

CSS
.box {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
}

Total width: 200 + 40 + 10 = 250px. Margin adds space outside this width.

Use border-box

border-box includes padding and border inside the declared width, which makes sizing more predictable.

CSS
* {
  box-sizing: border-box;
}