Loading lessons...
Margins, Padding & the Box Model
Every element is a box. Let's meet its four layers.
The box model
- From the inside out: 1. Content, the text or image.
- Padding, space INSIDE the border (pushes content away from edges).
- Border, the edge line (can be invisible).
- Margin, space OUTSIDE the border (pushes the box away from neighbors).
Code
css
div {
width: 300px;
padding: 20px; /* space inside */
border: 5px solid; /* the edge */
margin: 15px; /* space outside */
}
Padding (inside)
Space between content and the border.
Code
css
p {
padding: 20px; /* all sides */
padding: 10px 20px; /* top/bottom, left/right */
padding-top: 5px; /* one side only */
}
Shorthand order for 4 values: top, right, bottom, left (clockwise).
Margin (outside)
Space between the border and neighbors.
Code
css
p {
margin: 20px;
margin: 10px 5px; /* vertical, horizontal */
margin-top: 0;
}
margin: auto centers a block element horizontally!
Margin collapse
Two vertical margins collapse (merge) into the bigger of the two. This is normal CSS behavior, don't panic.
Width and the box model
width sets the content width by default. Padding/border then ADD to the total size. To force the width to include padding + border, use:
Code
css
- {
box-sizing: border-box;
}
This is the modern best practice, width then means "total width".
TL;DR
- Box = content + padding + border + margin.
- padding = inside, margin = outside.
- Shorthand order clockwise: top right bottom left.
margin: autocenters a block.- Margins collapse vertically.
box-sizing: border-boxincludes padding & border in width.