Free beginner tutorial

CSS Box Model: Margin, Border and Padding

The CSS box model explains how the browser calculates the space an element occupies. Each box has content, padding, a border and a margin.

The four parts of a CSS box

  • Content: Text, images or other page content.
  • Padding: Space between content and the border.
  • Border: The edge around padding and content.
  • Margin: Space outside the border that separates neighboring elements.

Set box dimensions

.card {
  width: 320px;
  padding: 20px;
  border: 2px solid #dce3eb;
  margin: 16px;
}

With the default content-box sizing, width applies to the content. In this example the border-box width is 320 + 20 + 20 + 2 + 2 = 364 pixels. The 16-pixel margins add space outside that box, so two such cards also need room between and around them.

Use border-box for predictable sizing

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

With border-box, the declared width includes the content, padding and border. In the same example, the border-box stays 320 pixels wide and the content area becomes 276 pixels. Margins remain outside the declared width.

Margins can collapse vertically between block elements. Padding never collapses and remains inside an element's border.