Lesson 9 +10 XP

Margins, Padding & the Box Model

Margins, Padding & The Box Model

Every element is a box. Let's meet its four layers.

The box model

From the inside out:

  1. Content, the text or image.
  2. Padding, space INSIDE the border (pushes content away from edges).
  3. Border, the edge line (can be invisible).
  4. Margin, space OUTSIDE the border (pushes the box away from neighbors).
div {
  width: 300px;
  padding: 20px;      /* space inside */
  border: 5px solid;  /* the edge */
  margin: 15px;       /* space outside */
}

Padding (inside)

Space between content and the border.

p {
  padding: 20px;               /* all sides */
  padding: 10px 20px;          /* top/bottom, left/right */
  padding-top: 5px;            /* one side only */
}

Shorthand order for 4 values: top, right, bottom, left (clockwise).

Margin (outside)

Space between the border and neighbors.

p {
  margin: 20px;
  margin: 10px 5px;   /* vertical, horizontal */
  margin-top: 0;
}

margin: auto centers a block element horizontally!

Margin collapse

Two vertical margins collapse (merge) into the bigger of the two. This is normal CSS behavior, don't panic.

Width and the box model

width sets the content width by default. Padding/border then ADD to the total size. To force the width to include padding + border, use:

* {
  box-sizing: border-box;
}

This is the modern best practice, width then means "total width".

TL;DR

  • Box = content + padding + border + margin.
  • padding = inside, margin = outside.
  • Shorthand order clockwise: top right bottom left.
  • margin: auto centers a block.
  • Margins collapse vertically.
  • box-sizing: border-box includes padding & border in width.