2.4 The Box Model: Padding, Border, Margin
This is the most important — and most confusing for beginners — concept in CSS: every element on a page is essentially a rectangular "box." Understand the box and you understand half of web layout.
Every box has four layers from inside out:
The lab below has three sliders. Drag them and watch with your own eyes how padding, border, and margin change a box's size and spacing.
Loading interactive lab...
The four layers of a box
- content: innermost, holding the real content — text, images.
- padding: the space between content and border, pushing content outward.
- border: the edge wrapping the padding.
- margin: the space outside the border, pushing this box away from other elements.
css
.box {
padding: 16px; /* 16px around the content */
border: 2px solid #333; /* a 2px solid border */
margin: 24px; /* 24px outside the box */
}Loading concept check...
padding or margin? The most common confusion
Both are "blank space"; the difference is which side of the border they sit on:
- padding (inner): makes the box's inside roomier; the background color extends into the padding.
- margin (outer): pushes the box away from its neighbors; it's transparent, with no background.
One line to remember: want content farther from the border → padding; want the box farther from other boxes → margin.
Loading concept check...
Each side can be set separately
Both padding and margin can target top, right, bottom, left individually:
css
.box {
padding-top: 8px;
padding-bottom: 8px;
margin-left: 16px;
/* Shorthand: top right bottom left (clockwise) */
padding: 8px 16px 8px 16px;
/* Two values: top-bottom left-right */
margin: 10px 20px;
}Note
A common trap: the box is bigger than you expect. By default, the
width you set is only the content width; padding and border are added outside it, making the total wider. Adding box-sizing: border-box; makes width mean "total width including padding and border," which makes layout far more intuitive — it's nearly standard in every project.Loading practice...