The CSS Box Model (Deep but Practical)
Content, padding, border, margin; box-sizing; and how it affects layout calculations.
On this page
30‑second interview answer
Every element is a rectangle: content → padding → border → margin. box-sizing controls whether width/height include padding/border. With content-box (default) width applies to content only; with border-box width includes padding and border, which makes layouts more predictable—so many projects set box-sizing: border-box globally.
The layers
- Content: the actual text/image area
- Padding: space inside border
- Border: the border line
- Margin: space outside border
box-sizing: the important part
Default behavior:
.box { box-sizing: content-box; }If you set:
.box { width: 200px; padding: 20px; border: 2px solid; }Then total rendered width is 200 + 40 + 4 = 244px.
With border-box:
.box { box-sizing: border-box; }Total width stays 200px (padding/border included).
Common global reset
*, *::before, *::after {
box-sizing: border-box;
}Margin collapse (interview favorite)
Vertical margins can collapse between block elements.
Example:
h1 { margin-bottom: 20px }p { margin-top: 20px }
Distance might be 20px, not 40px.
Ways to avoid surprises:
- use padding instead of margins for spacing in some layouts
- use flex/grid containers (margin collapse behaves differently)
- add
overflow: auto/display: flow-rooton container (with care)
Practical debugging tips
- Use DevTools “box model” overlay.
- Check computed width/height.
- Watch for
box-sizingmismatch.
Mini Q&A
Q1: What does box-sizing: border-box do?
- Includes padding and border in width/height.
Q2: What is margin collapse?
- Adjacent vertical margins combine into one.
Q3: Why set border-box globally?
- Predictable sizing.
Summary checklist
- I know all layers of the box model.
- I can explain border-box vs content-box.
- I understand margin collapse basics.
- I can debug sizing in DevTools.
Looking for structured, offline interview prep?
Free online lessons • Portable Amazon Kindle / Paperback
Frontend Interview Guide (2025 Edition)
By Rajesh Dhiman
Comprehensive preparation covering React internals, Web Performance, CSS architecture, and system design questions.
JavaScript Interview Guide
By Rajesh Dhiman
Deep dive into the Event Loop, microtask draining, closures, prototypal inheritance, and asynchronous execution patterns.
Note: All lessons on Frontend Interview remain completely free to read online. As an Amazon Associate, we may earn from qualifying purchases.
Written by Rajesh Dhiman
Authored by Rajesh Dhiman and engineered at Eunix Tech. Focused on deep-dive frontend engineering, JavaScript runtime internals, React architecture, and web performance.