CSS margin

Margin in the CSS box modelMargin 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

div {border:1px solid dodgerblue}
h2, h3, h4, h5 {margin:0; background:lightpink}
h2 {margin-top:2em}
h3 {margin-right:2em}
h4 {margin-bottom:2em}
h5 {margin-left:2em}
<div><h2>h2 with top margin</h2></div>
<div><h3>h3 with right margin</h3></div>
<div><h4>h4 with bottom margin</h4></div>
<div><h5>h5 with left margin</h5></div>

Output

Margin on all sides

Like the border shorthand notations you can change all margins with a single margin rule.

CSS margin

div {border:1px solid dodgerblue}
h2, h3, h4, h5 {margin:0; background:lightpink}
h2 {margin:1em}
h3 {margin:1em 0}
h4 {margin:1em 0 2em}
h5 {margin:1em 2em 3em 4em}
<div><h2>h2 uses 1em margin for all sides</h2></div>
<div><h3>h3 has 1em margin for the top and bottom and 0 margin for the left and right side</h3></div>
<div><h4>h4 has 1em margin for the top, 0 for the left and right side and 2em for the bottom</h4></div>
<div><h5>h5 uses a different margin for each side going from top to right, bottom and left</h5></div>

Output