Lesson · HTML & CSS Basics
The box model and spacing
Every visible element occupies a box, and understanding its layers prevents layout surprises.
What you will learn
- Identify the box model layers
- Distinguish margin from padding
- Use box-sizing for predictable widths
Four layers form a box
The content area holds text or other child elements. Padding adds space inside the border, the border surrounds the padding, and margin creates separation outside the border. A background typically paints the content and padding area. These layers explain why two elements with the same declared width can occupy different total space.
Calculate before adjusting
With the default content-box model, declared width applies to the content only. Padding and border add to the rendered width. border-box includes padding and border inside the declared width, which often makes responsive sizing easier to reason about. A small global box-sizing rule is a common starting point.
Use spacing intentionally
Margin separates neighboring boxes; padding gives content room inside its own box. Vertical margins can collapse in some block layouts, so the visible gap may not equal a simple sum. When spacing looks unexpected, inspect the computed box model rather than adding increasingly large values.
Preserve readable content
Fixed heights can clip text when a learner zooms or when a heading wraps on a narrow screen. Prefer content-driven height and use padding to create breathing room. The browser should be allowed to accommodate font scaling, translated text, and different viewport widths.
Let the box grow with its content
A card may contain a longer translation, larger text, or a line that wraps on a phone. A fixed height can clip that content and hide a focus outline. Prefer a minimum size when a baseline is needed, and allow the box to grow. Inspect both the computed dimensions and the actual content before changing spacing.
*,
*::before,
*::after {
box-sizing: border-box;
}
.card {
width: 20rem;
padding: 1.25rem;
border: 1px solid #9bb3c8;
margin: 1rem;
}
Practice exercise
Give a card consistent internal spacing and a thin border without making its declared width grow unexpectedly.
Show a hint
Use border-box sizing and padding.
Show one possible solution
Apply box-sizing: border-box to the card, then set its width, padding, and border separately.
Quick check
Padding separates the content from the border; margin separates the element from its neighbors.