Chapter 1CSS · Theory

Box Model

Every element is a rectangular box with content, padding, border, and margin areas.

The CSS box model describes the rectangular boxes generated for each element. From inside out: content area (width/height), padding (space between content and border), border (visible edge), and margin (space outside the border that separates elements from each other).

box-sizing: content-box (default) — width/height apply only to the content box, so padding and border are added on top. A 200px element with 20px padding is actually 240px wide.

box-sizing: border-box — width/height include padding and border. A 200px element stays 200px regardless of padding. This is almost always what you want. Apply universally with: *, *::before, *::after { box-sizing: border-box; }.

Margin collapsing: adjacent vertical margins of block elements collapse to the larger value (not added together). This doesn't happen with flexbox/grid children.

┌──────────────────────────────────┐
│           margin                 │
│  ┌────────────────────────────┐  │
│  │         border             │  │
│  │  ┌──────────────────────┐  │  │
│  │  │       padding        │  │  │
│  │  │  ┌────────────────┐  │  │  │
│  │  │  │    content     │  │  │  │
│  │  │  └────────────────┘  │  │  │
│  │  └──────────────────────┘  │  │
│  └────────────────────────────┘  │
└──────────────────────────────────┘
Diagram: Box Model