What is the CSS box model?

Every HTML element is a rectangular box made of content, padding, border, and margin understanding these four layers is fundamental to layout.

CSSLayout

Overview

The CSS box model describes how much space an element takes up. Every element is surrounded by four layers: the content area, padding, border, and margin. By default `box-sizing: content-box` means width/height only cover the content padding and border are added on top. Switching to `border-box` is the modern standard.

Key Points

  • •Content: the actual text or image inside the element.
  • •Padding: transparent space between the content and the border.
  • •Border: a line drawn around the padding and content.
  • •Margin: transparent space outside the border, separating elements from each other.
  • •`box-sizing: border-box` makes width/height include padding and border far more predictable.

Examples

The four layers of the box model

css
.box {
  width: 200px;
  padding: 16px;       /* space inside */
  border: 2px solid;   /* drawn around padding */
  margin: 24px;        /* space outside */
}
/* With content-box (default): total width = 200 + 16*2 + 2*2 = 236px */
/* With border-box:             total width = 200px exactly            */

Apply border-box globally (recommended)

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

Most CSS resets and frameworks include this. Add it to every project.

Visualise the box model in DevTools

text
Open Chrome DevTools → Elements → Computed tab
The coloured diagram shows margin (orange), border (yellow),
padding (green), and content (blue) for any selected element.

Pro Tip

Always add `box-sizing: border-box` globally. Without it, adding padding to an element changes its rendered size and breaks layouts in surprising ways.