Give space to auto margins in the main direction
If there’s no space left, auto
margins are zero.
There’s no space to claim for these auto
margins.
It’s as though no margin
was set at all.
If there is space, each auto
margin gets an even chunk of that space.
If you only have one flex item with an auto
margin, it will get all the space.
If you have two, the space is divided up among the two margins equally, and so on.
auto
margins are great for “pushing flex items apart”.
A great example of this is a page header with a logo and a bunch of links.
Let’s say the logo and the links are all list item elements (<li>
).
You want to have the logo on one side, and all the links on the other side.
You can achieve this by setting an auto
margin on either the logo, or the link directly next to the logo.
Create complex behavior by combining auto
margins and regular
alignment.
Imagine you have a bunch of tags that you want centered if they can all fit on the page.
But if they don’t fit on the page, you want them to be horizontally scrollable instead.
You can’t just say : center
, because then the items will overflow on both sides, and one side won’t be reachable by scrolling.
Instead, you can set auto
margins on the first and last flex items on the side “facing the flex container’s edge”. That will center the tags because the first and last flex item will be claiming that remaining space.
Then, keep the initial : flex-start
. When the tags are longer than the flex line and overflow, there won’t be any space for the auto
margins to claim. But the flex-start
alignment will still work, and the flex items will be a scrollable list you can reach.