ilyo ilyo - 1 month ago 15
CSS Question

When does flex switch from grow to shrink?

I don't understand what makes flex items switch from grow to shrink behavior? At first I thought it is the

flex-basis
value, but what if only one item has it, or none?

Also, the specs on
flex-basis
say:


The flex-basis CSS property specifies the flex basis which is the initial main size of a flex item.


What does that mean? If I have one item with it, and the rest are default, why is it usually starts a little bigger than the value? Where does the added space come from?

Answer

The flex-basis property sets the initial main size of the flex item, before free space is distributed by other flex properties.

This means that the flex item is first sized for its defined width (in flex-direction: row) or height (in flex-direction: column).

In other words, in a row-direction flex container, where flex-basis: 100px is equivalent to width: 100px, the item would have a width of 100px.

That's the initial main size.

THEN, other flex properties are applied. Namely, flex-grow and flex-shrink.

If the flex container is wider than 100px, then flex-grow: 1 expands the item to fill the extra space.

If the flex container is less than 100px, then flex-grow: 1 is ignored and flex-shrink: 1 would reduce the size of the item according to a flex sizing algorithm.

So, to answer your question:

When does flex switch from grow to shrink?

Assuming both properties are enabled (i.e., they are not flex-grow: 0 or flex-shrink: 0), the switch will occur when the sum total of flex-basis / width / height on flex items is no longer less or more than the length of the container.

To make this a bit more clear:

  • When the sum total of flex-basis / width / height on flex items is no longer more than the length of the container, this means there is no overflow and the items don't consume all available space. flex-grow works.

  • When the sum total of flex-basis / width / height on flex items is no longer less than the length of the container, this means there is overflow and the items must shrink to fit inside the container. flex-shrink works.

From the spec:

flex-grow

This [property] specifies the flex grow factor, which determines how much the flex item will grow relative to the rest of the flex items in the flex container when positive free space is distributed.

flex-shrink

This [property] specifies the flex shrink factor, which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed.

flex-basis

This [property] specifies the initial main size of the flex item, before free space is distributed according to the flex factors.

https://www.w3.org/TR/css-flexbox-1/#flex-property