HTML & CSS Foundations · 16 min · 120 XP

Box model and spacing

Content, padding, border and margin, the one reset that makes widths behave, and spacing with gap.

Every element is a box made of four layers: content, then padding (space inside the border), then border, then margin (space outside, between boxes). Padding takes the element's background; margin is transparent.

By default (box-sizing: content-box), width sets only the content. Padding and border are added on top, so a 300px card with 20px padding and a 1px border is actually 342px wide, and it overflows its 300px column. Almost every modern stylesheet starts with one rule that makes width mean the whole box:

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

Shorthands go clockwise from the top: padding: 8px 16px is 8 top and bottom, 16 left and right; four values are top, right, bottom, left. Vertical margins between blocks collapse: two 16px margins make 16px of space, not 32. For space between items in a flex or grid container, prefer gap on the container over margins on every child: it never doubles up and never leaves stray space after the last item.

Loading your workspace…