HomeGuideLabGlossary

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.

1AThis margin is 0

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.

Remaining space112A2

If you have two, the space is divided up among the two margins equally, and so on.

Remaining space112AA2

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.

AboutProjectsHello,well yes, welcome to my personal home page

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.

AboutAAboutProjectsProjectsA

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.

MusicComicsCoffee

But if they don’t fit on the page, you want them to be horizontally scrollable instead.

MusicComicsCoffeeScroll to see me

You can’t just say : center, because then the items will overflow on both sides, and one side won’t be reachable by scrolling.

MusicComicsCoffeeScroll to see meCan’t reach me...justify-content: center

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.

MusicComicsCoffeeAA

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.

AMusicComicsCoffeeAjustify-content: flex-start