Four layers of a box
Every element is a rectangular box built from four nested layers. From the inside out you have the content area, then padding, then border, then margin. Background color and images paint behind the content and padding but stop at the border edge.
- Content holds text, images, or child boxes.
- Padding is space inside the border that shares the background.
- Border wraps the padding and has its own color and width.
- Margin is transparent space pushing other boxes away.
How sizing changes the math
The box sizing property decides what a width value means. With the default content box, a width sets only the content area, so padding and border add on top and the visible box grows wider than expected. With border box, the width includes padding and border, so the box stays the declared size and the content area shrinks to fit.
- content box width equals content only.
- border box width equals content plus padding plus border.
- Many resets set border box on every element for predictable layouts.
Key idea
A box is content, padding, border, and margin stacked outward, and the box sizing property decides whether a width counts the padding and border or just the content.