spacing
margin
Shorthand for setting outer spacing on all four sides of an element. Accepts lengths, percentages, or the auto keyword for horizontal centering.
margin: <top> <right> <bottom> <left> | <top> <horizontal> <bottom> | <vertical> <horizontal> | <all> Common values
| Value | Effect |
|---|---|
| 0 | Removes all outside spacing |
| auto | Distributes remaining space equally, useful for horizontal centering |
| 1rem | Equal 1rem margin on all sides |
| 1rem 0 | Vertical margin only |
| 1rem 2rem | Vertical then horizontal margin |
Examples
.container { margin: 0 auto; max-width: 960px; } Classic horizontally-centered container
p { margin: 0 0 1rem; } Rhythm spacing between paragraphs
.card { margin: 1rem 2rem; } Different vertical and horizontal margins
Gotcha
Vertical margins between block siblings collapse into the larger of the two; flex and grid items do not collapse.
Related properties
padding
Shorthand for inner spacing between an element's content and its border. Padding never collapses and adds to an element's rendered footprint unless box-sizing: border-box is set.
width
Sets the horizontal size of an element's content box (or border box if box-sizing: border-box). Modern intrinsic keywords give sizing that adapts to content.
box-sizing
Controls whether an element's declared width and height include padding and border. border-box is the modern default most stylesheets set globally.
gap
Shorthand for row-gap and column-gap, setting spacing between flex, grid, or multi-column items. Replaces margin hacks for evenly spacing children.
height
Sets the vertical size of an element. Viewport units like vh, dvh, and svh are common for full-screen sections and account for mobile browser chrome.