Skip to the workspace
Pebellslearn by building
CSS  ›  Lesson

The Box Model

CSS 14 minEvery element is a box of content, padding, border and margin, and box-sizing decides whether width covers only the content or also the padding and border.

frontend / The Box Model

Explore each scene at your own pace.

01 · The rule

The rule

The Box Model

You set each menu card on the bakery page to width: 300px, three in a row inside a 900-pixel container. They should fit exactly. Instead the third card drops to a new line. Nothing is broken: the cards are simply wider than you think, and the box model explains why.

The rule

Every element is a box: content, then padding, then border, then margin.

From the inside out:

  • Content: the text or image itself.
  • Padding: space inside the box, between the content and the border. It takes the element's background colour.
  • Border: the line around the padding.
  • Margin: space outside the border, pushing other boxes away. It is always transparent.
.card {
  width: 300px;
  padding: 20px;
  border: 2px solid tan;
  margin: 10px;
}

The width surprise. By default (box-sizing: content-box), width sets only the content. Padding and border are added on top:

300 + 20 + 20 + 2 + 2 = 344 pixels of visible card, plus 10 pixels of margin on each side.

The fix most projects use. Switch every element to border-box, where width includes padding and border:

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

Now the same card is exactly 300 pixels wide, and the content area shrinks to 256 to make room.

Shorthand order. padding: 10px 20px means 10 top and bottom, 20 left and right. Four values run clockwise from the top: margin: 5px 10px 15px 20px is top, right, bottom, left.

Margin collapse. When two vertical margins meet, for example a heading with margin-bottom: 24px above a paragraph with margin-top: 16px, they do not add up. The gap is the larger one, 24 pixels. Horizontal margins never collapse.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.