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.

alt text

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:


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:

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:

Inline:


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:


Section 3.8: Gotchas


Summary


Resources