Sub topic 14
Pushing items apart with auto margins
This chapter assumes you can write a flex container with display: flex, know the main axis from the cross axis, and understand justify-content. You should also know the box model, because auto margins are ordinary margins with a special value.
How auto margins behave in flexbox
In normal block layout, margin-left: auto on a block with a set width pushes it to the right. In a flex container, auto margins are more powerful. Before justify-content runs, the browser gives all free space on the main axis to the auto margins. If an item has an auto margin, that margin takes the space, and justify-content has nothing left to distribute.
This lets you split a row into groups without extra wrapper elements.
.toolbar {
display: flex;
align-items: center;
}
.toolbar .push-right {
margin-left: auto;
}The auto left margin on .push-right absorbs all free space. That item, and every item after it, moves to the far end of the row.
Common uses
- A toolbar with a few items on the left and an action on the right.
- A card whose button sits at the bottom. In a column flex container,
margin-top: autoon the button pushes it down. - Centering one item both ways with
margin: auto.
The card example looks like this:
.card {
display: flex;
flex-direction: column;
min-height: 12rem;
}
.card .button {
margin-top: auto;
}The button sits at the bottom of every card, even when the text above it is short.
Rules to remember
- Auto margins only absorb free space. If the items already fill the line, there is no space and the margin computes to zero.
- If several items have auto margins, the free space is divided equally among them.
- Auto margins on the cross axis also work.
margin-top: autoin a row container moves one item to the bottom of the line, and it overridesalign-itemsfor that item. - An item with
flex-growabove zero takes the free space first. Auto margins then get none, so a growing item next to an auto margin makes the margin appear to do nothing.
Auto margins or justify-content
Use justify-content when the whole group should be distributed the same way. Use auto margins when only one place in the row needs a gap, or when one item needs different treatment from the rest. justify-content: space-between also puts equal gaps between every pair of items, which is wrong for a "logo and links on the left, login on the right" layout.
Exercise
A row container has three items and justify-content: flex-start. You add margin-left: auto to the second item. Where do the three items end up, and what happens if you also set flex-grow: 1 on the third item?
Show answer
The first item stays at the left edge. The second and third items move to the right edge, because the auto margin on the second item absorbs all the free space. If the third item also has flex-grow: 1, it takes the free space first, so the auto margin becomes zero and the items sit together, with the third one stretched.