Margin
margin
property sets the margin area of an element (the distance between the element and adjacent elements).

Basic Concepts
Margin Positions
There are 4 positions for a margin: top, right, bottom, left (remember: clockwise direction).
Additionaly, you can also specify margin positions based on the direction of writing (these would be based on writing-mode
, direction
, and text-orientation
values):
- Inline direction — is the direction of writing (e.g. left-to-right, right-to-left, top-to-bottom)
- Block direction — is the direction perpendicular to inline position (i.e. the direction of how you add new lines to your paragraph)
Margin Collapsing
When vertical margins (top and bottom) of different elements touches each other, the margin "collapses" into one single margin.
It does not apply to:
- horizontal margins (left and right),
- margins of floating elements, and
- margins of absolutely positioned elements.
Common Margin Properties
margin
Sets the top, right, bottom, and left margins of an element in one declaration (remember: clockwise direction).
If you specify less than 4 lengths, the missing lengths would be inferred from the lengths that you specified (it will try to make symmetrical margins).
Possible length values:
- length — E.g.
10px
or2em
. You can also specify negative values. - percentage — E.g.
10%
. Sets the margin relative to the container's width. auto
— Sets the margin automatically. Can be used for horizontal centering, but not for vertical centering.
Note that the vertical margins collapses into one.
margin-top
Sets the element's top margin. (See margin
.)
margin-right
Sets the element's right margin. (See margin
.)
margin-bottom
Sets the element's bottom margin. (See margin
.)
margin-left
Sets the element's left margin. (See margin
.)
Obscured Margin Properties
margin-inline-start
Sets the margin at the start of "inline" direction. (If you're writing horizontally from left to right, then it maps to margin-left
.)
margin-inline-end
Sets the margin at the end of "inline" direction. (If you're writing horizontally from left to right, then it maps to margin-right
.)
margin-inline
Shorthand for margin-inline-start
and margin-inline-end
.
p {
margin-inline: <margin-inline-start> <margin-inline-end>;
margin-inline: <margin-inline-start>;
}
margin-block-start
Sets the margin at the start of "block" direction. (If you're writing horizontally from left to right, then top to bottom, then it maps to margin-top
.)
margin-block-end
Sets the margin at the end of "block" direction. (If you're writing horizontally from left to right, then top to bottom, then it maps to margin-bottom
.)
margin-block
Shorthand for margin-block-start
and margin-block-end
.
div {
margin-block: <margin-block-start> <margin-block-end>;
margin-block: <margin-block-start>;
}
References
- margin (MDN) — https://developer.mozilla.org/en-US/docs/Web/CSS/margin
- margin (CSS-Tricks) — https://css-tricks.com/almanac/properties/m/margin/