Frontend Master

JavaScript Curriculum

The Box Model
+55 XP

The Box Model

easy
~30 min·55 XP

Your coffee shop cards look cramped — text touching the border, cards touching each other. The fix is one concept: the box model. Once you see it, you can't unsee it.

The Box Model

Every single element on a webpage — every <p>, every <div>, every <button> — is a rectangular box. Understanding this box, and how it's measured, unlocks all of CSS layout.

The Four Layers

A CSS box has four layers from outside in:

box-model.css
margin24px
border4px
padding16px
content-box width
120px (fixed)
total rendered width
160px
margin 24px
border 4px
padding 16px
content
CSS
.box {
  width: 120px;       /* content width */
  margin: 24px;
  border: 4px solid #333;
  padding: 16px;
  /* total rendered width: 160px */
}
ℹ️What each layer does
**Margin** — transparent space outside the border. Pushes other elements away. Never shows background color. **Border** — the visible edge of the element. Can have width, style, and color. **Padding** — space between the border and the content. Shows the element's background color. **Content** — where your text, images, and child elements live.

box-sizing — The Most Important Reset

By default, CSS uses box-sizing: content-box — which means width only applies to the content area. Padding and border get added on top. This makes width calculations painful.

The fix: box-sizing: border-box — makes width include padding and border. The element stays exactly the size you declare.

box-sizing.css
width200px
padding20px
border4px
box-sizing: content-box(default)

width = content only. Padding + border added on top → element grows beyond 200px.

content
content width200px
+ padding × 2+40px
+ border × 2+8px
total rendered248px
box-sizing: border-box(recommended)

width = content + padding + border. Element stays exactly 200px wide — predictable.

content
total = width200px
− padding × 240px
− border × 28px
content width152px
💡Always add this reset at the top of your CSS
Every professional CSS project starts with this one rule: ```css *, *::before, *::after { box-sizing: border-box; } ``` It makes every element use border-box sizing. Add it before anything else — always.

Margin vs Padding — Know the Difference

The most common beginner confusion: when to use margin vs padding. One question settles it every time: is the space inside or outside the border?

margin-vs-padding.css1/4
Scenario

You want space BETWEEN two cards in a list

Your Challenge

Apply the box model to the coffee shop page — add proper padding inside cards, margin between them, and set up the border-box reset.

Challenge

Style the .card element with: 24px padding, a 2px solid border, 16px margin-bottom, border-radius of 8px, and set box-sizing: border-box on * so widths are predictable. Then give the body a max-width of 720px centered with margin: 0 auto.

box-modelmarginpaddingbordercontentbox-sizingborder-boxcontent-boxwidthheight
The Box Model | Nexus Learn