CSS: Box Model
What you will learn
Every HTML element is a rectangular box. The box model describes the layers from the content outward: content, padding, border, and margin.
The four layers
div {
width: 200px;
height: 100px;
padding: 20px; /* space inside the border */
border: 2px solid black;
margin: 10px; /* space outside the border */
}
From inside to outside:
- Content — the actual text or child elements. Sized by
widthandheight. - Padding — space between content and border. Transparent by default. Background color extends into padding.
- Border — visible edge. Can be styled with
border-width,border-style,border-color. - Margin — space outside the border, separating this element from others. Transparent. Collapses vertically.
box-sizing: border-box
By default (content-box), the width and height you set only apply to the content. Padding and border are added on top, making the element bigger than you expected.
/* Default: content-box */
div { width: 200px; padding: 20px; border: 2px solid black; }
/* Actual width = 200 + 20*2 + 2*2 = 244px */
/* border-box: width INCLUDES padding and border */
div { box-sizing: border-box; width: 200px; padding: 20px; }
/* Actual width = 200px (content shrinks to fit) */
Most developers apply border-box globally with *, *::before, *::after { box-sizing: border-box; }.
Margin collapsing
Vertical margins collapse: if a <p> has margin-bottom: 20px and the next <p> has margin-top: 30px, the gap between them is 30px (the larger one wins), not 50px.
Common mistakes
- Forgetting
box-sizing: border-box— causing elements to be wider than expected. - Confusing padding and margin — padding adds space inside the border (affects background area), margin adds space outside.
- Setting
widthandpaddingwithout considering the box model math. - Using negative margins for layout — can cause unexpected overlaps.
Quick check below!