Property margin
Sets all the margin properties in one declaration
- When one value is specified, it applies the same margin to all four sides.
- When two values are specified, the first margin applies to the top and bottom, the second to the left and right.
- When three values are specified, the first margin applies to the top, the second to the right and left, the third to the bottom.
- When four values are specified, the margins apply to the top, right, bottom, and left in that order (clockwise).
Horizontal centering
In modern browsers
display: flex; justify-content: center;
In older browsers
margin: 0 auto;
Margin collapsing
Elements’ top and bottom margins are sometimes
collapsed into a single margin that is equal to
the larger of the two margins.
Note that the margins of floating and absolutely
positioned elements never collapse.
Margins don’t collapse in a container with
display set to flex or grid.
Collapsing margins is only relevant in the
vertical direction.
Margin collapsing occurs in three basic cases:
- Adjacent siblings. The margins of adjacent
siblings are collapsed. - No content separating parent and descendants.
- Empty blocks.
If there is no border, padding, inline content,
height, or min-height to separate a block’s
margin-top from its margin-bottom, then its top
and bottom margins collapse.
Values
auto
The browser selects a suitable margin to use. For
example, in certain cases this value can be used
to center an element.
<percentage>
The size of the margin as a percentage, relative
to the inline size (width in a horizontal
language, defined by writing-mode) of the
containing block.
<length>
The size of the margin as a fixed value.
Syntax
/* Apply to all four sides */
margin: 1em;
margin: -3px;
/* top and bottom | left and right */
margin: 5% auto;
/* top | left and right | bottom */
margin: 1em auto 2em;
/* top | right | bottom | left */
margin: 2px 1em 0 auto;
/* Global values */
margin: inherit;
margin: initial;
margin: revert;
margin: revert-layer;
margin: unset;