Margin
Create space outside an element's border.
Syntax
margin: top right bottom left;The margin property adds space outside the border. You can set each side separately or use shorthand.
margin: 20px;— all four sides.margin: 10px 20px;— top/bottom, then left/right.margin: 5px 10px 15px 20px;— top, right, bottom, left.
Set margin: 0 auto; to horizontally center a block element with a fixed width.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer uses margin: 0 auto on a fixed-width container to center it horizontally within the browser window.
- A designer uses margin-bottom on headings to create consistent vertical rhythm between sections.
- A developer debugs a gap above the page body and discovers margin collapsing between the first child and its parent was the cause.
More examples
Centering a block with auto margin
Sets top/bottom margin to 0 and left/right to auto, causing the browser to equally split horizontal space and center the block.
.container {
width: 960px;
max-width: 100%;
margin: 0 auto;
}Shorthand margin four directions
Demonstrates the margin shorthand: four-value clockwise (T R B L) and two-value vertical/horizontal forms.
/* top right bottom left */
.card { margin: 16px 24px 32px 24px; }
/* vertical | horizontal */
.section { margin: 48px auto; }Preventing margin collapse
Uses overflow: hidden to establish a block formatting context, preventing the child's margin from collapsing into the parent.
.parent {
/* overflow: hidden triggers a BFC and stops margin collapse */
overflow: hidden;
background: #eef3ff;
}
.child {
margin-top: 24px;
}
Discussion