Chapter 3: The Box Model & Layout Calculation
Understand how browsers size and position elements and why CSS isn’t broken, you just weren’t told how it works
If your layout feels off unexpected spacing, weird scrollbars, things not lining up, the root cause is almost always the box model.
This chapter is here to fix that forever.
Section 3.1: What Is the Box Model?
Every element on a web page is a rectangular box.
The box model defines how that box is structured, how it’s sized, and how it interacts with other boxes.
From the inside out:
- Content: Your actual text/image/etc.
- Padding: Space between the content and the border
- Border: The border around the element
- Margin: Space between this element and others
Section 3.2: content-box
vs border-box
content-box
(default)
width: 200px;
padding: 20px;
border: 2px solid;
200px refers to the content only. Total width becomes 244px.
border-box
box-sizing: border-box;
200px includes padding + border. So content shrinks.
Use this globally:
*, *::before, *::after {
box-sizing: border-box;
}
Section 3.3: How Size Is Calculated
Browser does:
- Content size
- Add padding
- Add border
- Margin is outside this box
width: 300px;
padding: 10px;
border: 5px solid;
margin: 20px;
Total box width (with content-box
) = 330px
Section 3.4: Margin Collapse
If two vertical margins meet, the bigger one wins.
.a { margin-bottom: 30px; }
.b { margin-top: 20px; }
Resulting space between = 30px
Margins do not collapse horizontally.
Section 3.5: Inline vs Block
Block:
- Fills full width
- Stacks vertically
- Margin collapse applies
Inline:
- Flows in a line
- Width/height ignored
- Only
margin-left/right
respected
Section 3.6: Overflow
Controls what happens when content is too big.
overflow: hidden | auto | scroll;
You can target x/y separately:
overflow-x: auto;
overflow-y: hidden;
Section 3.7: DevTools for Debugging
Use Chrome DevTools → Computed tab → Box model
Colors:
- Blue = content
- Green = padding
- Yellow = margin
- Orange = border
Section 3.8: Gotchas
width: 100%
with padding causes overflow unless usingborder-box
- Inline elements don’t respect height
margin: auto
centers only with defined width- Borders can cause scrollbars
Summary
- Always set box-sizing: border-box
- Use DevTools to inspect layout visually
- Know when margin collapse occurs and how to stop it
- Use padding for inside space, margin for outside
- Use inline-block for inline-sized elements with layout rules
- Avoid surprise scrollbars by understanding overflow mechanics