14. Box Model Deep Dive: Margin
Margin is the space outside the border of an element. Its purpose is to create separation between adjacent elements. Margins are always transparent.
Setting Margin
Like padding, margin can be set individually or using shorthand, following the TRBL (Top, Right, Bottom, Left) order.
1. Individual Properties
css .heading { margin-top: 30px; /* Space above / margin-bottom: 20px; / Space below */ margin-left: 0; }
2. Shorthand Syntax
css /* All sides: 20px */ .box-1 { margin: 20px; }
/* Top/Bottom: 10px, Left/Right: 5px */ .box-2 { margin: 10px 5px; }
Key Concept: Centering with Auto Margin
For block-level elements (which we cover in detail soon) that have a defined width, setting the left and right margins to auto is the standard way to center the element horizontally on the page.
css .center-me { width: 600px; /* Must have a defined width! / margin: 0 auto; / 0 for top/bottom, auto for left/right */ border: 1px solid black; }
Margin Collapse (The Beginner Trap)
One of the trickiest concepts for beginners is Margin Collapse.
When two block-level elements are stacked vertically, their adjacent vertical margins (top and bottom) do not add up. Instead, they merge (collapse), and the element with the largest margin wins.
If h1 has margin-bottom: 30px and the following p has margin-top: 20px, the resulting vertical space between them is not 50px, but 30px (the larger of the two). Margin collapse only happens vertically, not horizontally.