HomeGuideLabGlossary

Shrink one flex item before others

The Solution at a Glance

This is a hack

There’s no explicit way to specify the order in which flex items should shrink. Each flex item either agrees to shrink, or it doesn’t.

12flex-shrink: 1flex-shrink: 0

But by playing with the values of flex-shrink, we can make it look like this order does exist.

You might want to make sure that other folks reading your code are aware of this hack, or that you mark it as a hack in some way. Future You counts as other folks!

Make one flex item shrink at a massively greater rate

How much each flex item is asked to shrink depends on its value of flex-shrink.

If you have one flex item with flex-shrink: 1 and one with flex-shrink: 10, the one with flex-shrink: 10 will be asked to shrink by more pixels than the one with flex-shrink: 1.

12flex-shrink: 10flex-shrink: 1

What we need to do is choose a flex-shrink value so huge that the flex item will be asked to do almost all the shrinking first.

NameNameNameN...AgeAgeAgeflex-shrink: 1flex-shrink: 123456789No need to shrinkshrinks firstcan’t shrink anymorestarts shrinking

When that flex item can’t shrink anymore because it reached its minimum size, the other flex items will be asked to shrink.

It works because shrinking happens in multiple rounds

The flex item with the huge flex-shrink value will be asked to do vastly more shrinking than the other flex item.

If it shrinks down to its minimum size and the flex items are still overflowing, then the flex container will start another round of shrinking.

NameThe flex items are still overflowing...Sorry, I can’t shrink anymore

But this time the huge-flex-shrink flex item won’t take part in it, because it can’t shrink anymore. So now the other flex items will have to shrink.

NameNameSure! , could you shrink, please?N...

How big should the flex-shrink value be?

It needs to be so big that the other flex items get asked to shrink by an amount so close to 0 pixels that it gets rounded down to 0 pixels.

To be pretty safe, you can use the highest value possible. There’s no official valid range for these values, but the browsers agreed to support numbers up to at least 134217727. That’s over a hundred and thirty million. It will do!