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.