The Box Model
You set each menu card on the bakery page to width: 300px, three in a row inside a 900-pixel container. They should fit exactly. Instead the third card drops to a new line. Nothing is broken: the cards are simply wider than you think, and the box model explains why.
The rule
Every element is a box: content, then padding, then border, then margin.
From the inside out:
- Content: the text or image itself.
- Padding: space inside the box, between the content and the border. It takes the element's background colour.
- Border: the line around the padding.
- Margin: space outside the border, pushing other boxes away. It is always transparent.
.card {
width: 300px;
padding: 20px;
border: 2px solid tan;
margin: 10px;
}The width surprise. By default (box-sizing: content-box), width sets only the content. Padding and border are added on top:
300 + 20 + 20 + 2 + 2 = 344 pixels of visible card, plus 10 pixels of margin on each side.
The fix most projects use. Switch every element to border-box, where width includes padding and border:
*, *::before, *::after {
box-sizing: border-box;
}Now the same card is exactly 300 pixels wide, and the content area shrinks to 256 to make room.
Shorthand order. padding: 10px 20px means 10 top and bottom, 20 left and right. Four values run clockwise from the top: margin: 5px 10px 15px 20px is top, right, bottom, left.
Margin collapse. When two vertical margins meet, for example a heading with margin-bottom: 24px above a paragraph with margin-top: 16px, they do not add up. The gap is the larger one, 24 pixels. Horizontal margins never collapse.
The shortcut
Before any width sum, ask one question: "Which box-sizing?" With content-box, add padding and border to the width. With border-box, the width is the answer. Then add margins outside if you need total space taken.
Measure the current card
content-box: 300 + 2 × 20 padding + 2 × 2 border = 344 pixels, before margins.
Drills
Answer fast — trust the rule.
With default content-box, how wide does width: 200px; padding: 10px; border: 1px solid; look?
The same box with box-sizing: border-box. How wide does it look?
Which layer takes the element's background colour?
An <h2> with margin-bottom: 30px sits above a <p> with margin-top: 20px. What is the gap between them?
What does margin: 0 auto 8px set?
Remember
- Every element is a box: content, then padding, then border, then margin.
- Ask "which box-sizing?" before any width sum; most projects set
border-boxeverywhere. - Trap: vertical margins collapse to the larger one instead of adding up.
