Box model and display
Content, padding, border, margin, box-sizing and the display types.
Updated
What the box model is
For CSS, every element is a box. The box has 4 layers, from the inside out:
margin — space outside the box, transparent
border — the border
padding — space between the border and the content, has the box's background
content — the text, the image
box-sizing — the most important line of CSS
By default (content-box), width applies only to the content. Padding and border are added on top:
.box { width: 200px; padding: 20px; border: 1px solid; }
/* content-box: real width = 200 + 20*2 + 1*2 = 242px 😬 */
/* border-box: real width = 200px, the content shrinks to 158px ✓ */That's why every modern project starts with:
*, *::before, *::after { box-sizing: border-box; }Tailwind includes it automatically (in preflight).
Display types
The display property decides how the box behaves:
| Value | Behavior | When |
|---|---|---|
block |
new line, full width, accepts width/height |
sections, paragraphs |
inline |
inside text, ignores width, height and vertical margin |
link, strong |
inline-block |
inside text, but accepts dimensions | badges, old-style buttons |
flex |
children along one axis | rows / columns — Flexbox |
grid |
children in rows and columns | 2D layout — Grid |
none |
the element disappears completely (takes no space either) | hiding |
display: none vs visibility: hidden vs opacity: 0: the first removes the element from the layout; the second hides it but keeps the space; the third makes it transparent, but it stays clickable.
Margin collapse
The vertical margins of two neighboring blocks don't add up — the larger one is used:
h2 { margin-bottom: 24px; }
p { margin-top: 16px; }
/* the space between them = 24px, not 40px */It doesn't happen in flex/grid. The modern solution: don't put margins on the children, put gap on the parent.
Sizes
| Property | Role |
|---|---|
width / height |
fixed size |
min-width / max-width |
limits — max-width: 65ch for readable text |
aspect-ratio: 16 / 9 |
a ratio, without padding hacks |
overflow: hidden / auto |
what to do with content that doesn't fit |
The rule: avoid a fixed height on containers with text — content varies, and the text will spill out of the box.
Summary
- The box = content + padding + border + margin.
box-sizing: border-boxeverywhere.displaydecides the behavior; flex and grid for layout.- Spacing between elements →
gapon the parent.