In both grid and flex layouts, auto margins absorb positive free space prior to alignment via the box alignment properties. Auto margins can therefore be used for alignment.
(This short note was inspired by Jen Simmons’s post on Twitter .)
By default, a grid item is stretched on both axes to fill its grid area:
The item can be aligned within its grid area using box alignment properties:
However, box alignment properties are inactive if the grid item has auto margins (
margin: auto;
centers the item on both axes):
Auto margins can also be applied partially to align the grid item differently:
By default, flex items are stretched on the cross axis and packed toward the start of the line on the main axis:
Auto margins center the items on both axes (which produces the same effect as applying
justify-content: space-around; align-items: center;
to the flex container):
In the following examples,
justify-content: space-around; align-items: center;
is applied to the flex container to demonstrate how these box alignment properties are affected by auto margins on the flex items.
Auto margins can be used to align flex items on the cross axis; the cross-axis alignment properties (
align-items
and
align-self
) are inactive when a flex item has cross-axis auto margins:
Similarly, auto margins take precedence over
justify-content
when distributing free space on the main axis (if one or more flex items have main-axis auto margins,
justify-content
is inactive):
However, if one or more flex items are flexible with a flex grow factor (
flex-grow
), any main-axis auto margins are set to zero (since there is no remaining free space after resolving the flexible lengths):