Every element is a rectangular box: content, padding, border, and margin. Layout bugs often come from margin collapse or forgetting box-sizing.
box-sizing: border-box
With border-box, width includes padding and border—setting width: 200px usually means “200px on screen,” which matches intuition for cards and grids.
Margin vs padding
- Padding — space inside the border (background extends here).
- Margin — space outside the border (separates siblings).
Practice
- Increase
.cardpadding—content breathes, border grows outward with border-box. - Change
marginon.card—see gap between cards. - Set
box-sizing: content-boxon one card and compare widths.
Important interview questions and answers
- Q: What does `box-sizing: border-box` change?
A: Width/height include padding and border, not only content. - Q: Padding vs margin?
A: Padding is inside the border; margin is outside between elements. - Q: Why do adjacent vertical margins sometimes collapse?
A: CSS collapses certain vertical margins between block siblings—use padding or flex/grid gaps when you need guaranteed spacing.