CSS Margin
March 11, 2008

Margin in the CSS box model
In addition to changing the CSS border and CSS padding of an element it's also possible to add space between its border and the surrounding elements.
This so-called margin completes the CSS box model that was introduced on the previous page. Again, all HTML elements follow this rule.
Margin on individual sides
To modify the margin of a single element side you can apply a length value to margin-top, margin-right, margin-bottom or margin-left.
CSS margin on individual sides:
- h2 {margin-top:2em; border:1px solid}
- h3 {margin-right:2em; border:1px solid}
- h4 {margin-bottom:2em; border:1px solid}
- h5 {margin-left:2em; border:1px solid}
Display:
h2 with top margin
h3 with right margin
h4 with bottom margin
h5 with left margin
Margin on all sides
Like the border shorthand notations you can change all margins with a single margin rule.
CSS margin:
- h2 {margin:1em; border:1px solid}
- h3 {margin:1em 0; border:1px solid}
- h4 {margin:1em 0 2em; border:1px solid}
- h5 {margin:1em 2em 3em 4em; border:1px solid}
Display:
h2 uses 1em margin for all sides
h3 has 1em margin for the top and bottom and 0 margin for the left and right side
h4 has 1em margin for the top, 0 for the left and right side and 2em for the bottom
h5 uses a different margin for each side going from top to right, bottom and left