CSS Box Model

The CSS box model describes every element as nested layers of content, padding, border, and margin.

Every element on a page is a rectangular box, and CSS builds that box from four layers wrapped around each other. Understanding how they stack is the foundation for controlling size and spacing anywhere on a page.

The four layers

  1. Content: the text, image, or other content at the center of the box.
  2. Padding: transparent space between the content and the border.
  3. Border: a line that wraps the padding and content.
  4. Margin: transparent space outside the border that separates the box from its neighbors.

All four layers on one element

<!DOCTYPE html>
<html>
<head>
<style>
.card {
  width: 220px;
  padding: 16px;
  border: 2px solid #cccccc;
  margin: 24px;
}
</style>
</head>
<body>

<div class="card">Box model demo</div>

</body>
</html>

Calculating the total size

By default the visible width of a box is the sum of its content width, its left and right padding, and its left and right borders. Margin adds space around the box but is not part of the box's own size.

LayerValueContributes to width?
Content220pxYes
Padding16px each sideYes (+32px)
Border2px each sideYes (+4px)
Margin24px each sideNo (spacing only)
Note: Add box-sizing: border-box to include padding and border inside the declared width, which makes totals much easier to predict. See CSS Padding and box-sizing.

Once the box model clicks, the CSS Margins and CSS Padding pages cover each layer in more depth.

Exercise: CSS Box Model

Going from the inside out, what is the correct order of the box model layers?