Aligning grid/flex items with auto margins

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 .)

Some of the examples below are too cramped when viewed on a smartphone in portrait mode. Please turn your device sideways to view those examples.

A grid container with one grid item

By default, a grid item is stretched on both axes to fill its grid area:

/* default */

The item can be aligned within its grid area using box alignment properties:

justify-self: end;
align-self: end;

However, box alignment properties are inactive if the grid item has auto margins ( margin: auto; centers the item on both axes):

justify-self: end;
align-self: end;
margin: auto;

Auto margins can also be applied partially to align the grid item differently:

margin-top: auto;
margin-left: auto;

A flex container with multiple flex items

By default, flex items are stretched on the cross axis and packed toward the start of the line on the main axis:

/* default */
/* default */
/* default */

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):

margin: auto;
margin: auto;
margin: auto;

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:

align-self: end;
margin-bottom: auto;
align-self: end;
margin-bottom: auto;

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):

/* default */
margin-left: auto;
margin-right: auto

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):

flex-grow: 1;
margin-left: auto;
margin-right: auto