Quiz
Warm-up from lesson 4-3: which wins, one ID selector or ten stacked class selectors?
The box model
Nearly every "why is there a gap here" and "why is this element wider than I said" bug in real work is a box-model question, which is why the first thing DevTools shows you about any element (lesson 9-1) is this exact diagram.
Every element the browser draws is a rectangular box with four layers, from the inside out:
- Content: the text or image itself.
- Padding: transparent space inside the border, pushing the border away from the content.
- Border: the (optionally visible) edge.
- Margin: transparent space outside the border, pushing neighbors away.
.card {
padding: 16px;
border: 2px solid #d4af37;
margin: 24px;
}Remember it as: padding is breathing room inside, margin is personal space outside. When two elements sit too close together, ask which one you mean before reaching for a property.
Per-side control and shorthand
Each layer can differ per side: padding-top, margin-left, border-bottom, and so on. The shorthands read clockwise from the top:
padding: 8px; /* all four sides */ padding: 8px 16px; /* top/bottom 8, left/right 16 */ padding: 8px 16px 24px 4px; /* top, right, bottom, left */
Borders take three parts, in any order: border: 2px solid black; (width, style, color).
One famous trick to memorize now: margin: 0 auto; on an element with a set width centers it horizontally. auto tells the browser to split the leftover space equally between left and right.
Quiz
What does padding: 10px 20px; mean?
Code exercise · javascript
By default an element's rendered width is its content width plus padding and border on BOTH sides (margin adds space outside but is not part of the box). Write totalWidth(content, padding, border) that computes the rendered width in pixels.