Align one flex item to opposite end from other flex items
The Solution at a Glance
- Have the flex container align the flex items in the main direction with
.
- Set an
auto
margin on a flex item to visually push it away from the other flex items.
Align the flex items in the main direction with
The flex container can align all flex items collectively, or distribute the space between them in some proportional way. You set on the flex container to do this.
This is nice, but it doesn’t give you precise control over the alignment of flex items in the main direction. There’s no way to say “all the flex items are aligned to this side, except these last two”.
Flex items themselves can’t use the justify-self
property in Flexbox layout, because the flex container collectively aligns and distributes flex items with . Only the flex container can align flex items in the main direction.
So we’ll set on the flex container to specify where most of the flex items should go.
Set an auto
margin on a flex item to push it away from others
Before any unused space in the flex container is offered to , this space gets offered to any
auto
margins of the flex items.
Because margins are not visible (background-color
doesn’t extend to the margin), they effectively “push” the visible part of the flex item in one direction or another.
The solution then is to make sure there’s an auto
margin between the group of flex items and the flex item that’s supposed to be aligned to the opposite end of the flex container.
All unused space in the flex container will be evenly distributed to any and all auto
margins.
This means there if you have at least one auto
margin, there will be no space left for to do anything! That’s because
aligns and distributes the margin boxes of the flex items, which now include the
auto
margin that expanded.