The CSS Box Model Explained: Margin, Border, Padding, and box-sizing

Every element on a page is a rectangle made of four layers: content, padding, border, margin. Once you can picture those four layers, 90% of CSS layout surprises disappear.
The four layers from inside out
- Content — the actual text or image
- Padding — space inside the border
- Border — the line around the padding
- Margin — space outside the border, between elements
The default that trips everyone up
By default, width: 200px sets the content width. Padding and border are added on top, so the element actually takes 200px + padding + border on screen. That's the classic 'why is my layout overflowing?' bug.
/* default — width is content only */
.box { width: 200px; padding: 20px; border: 2px solid; }
/* actual rendered width: 244px */The fix: box-sizing: border-box
*, *::before, *::after { box-sizing: border-box; }
.box { width: 200px; padding: 20px; border: 2px solid; }
/* actual rendered width: 200px */Margin collapsing — the other gotcha
Vertical margins between block elements collapse into the larger of the two. Two stacked elements with margin-top: 20px and margin-bottom: 30px end up 30px apart, not 50px.
Inspecting the box model in DevTools
Open DevTools, select any element, and check the Computed panel. You'll see a colour-coded diagram with the exact pixel values for each layer — the fastest way to debug spacing issues.
Common mistakes
- Forgetting box-sizing: border-box on inputs and buttons
- Using padding when margin is correct (or vice versa)
- Fighting margin collapse instead of using gap in flex/grid
Frequently asked questions
What does box-sizing: border-box actually do?
It makes width and height include padding and border, so the element renders at exactly the size you set.
Do flexbox and grid still use the box model?
Yes. Every element on the page is still a box — flex and grid just control how those boxes are arranged.
Keep reading
External references
Enjoyed this article?
Share it with a fellow developer or explore more tutorials in our blog.
More articles