Automatic minimum size of flex items
You can set a minimum size on any box in CSS, and the box will never be smaller than that size. You set the minimum size with these properties: min-inline-size
, min-block-size
, min-width
, min-height
.
By default, the initial value of these properties is auto
. What auto
means exactly depends on the type of layout being used.
In Flow layout, auto
means 0
.
In Flex layout, auto
is a bit more complex in the main direction.
In the cross direction, though, auto
is also 0
. In Flex layout, flex items are asked to shrink as needed to fit into the flex container’s content box.
By default, flex items agree to shrink because the initial value of flex-shrink
is 1
, which means “okay, I’ll shrink”. If you have a lot of flex items and a small flex container, then the flex items may be asked to shrink so much that they won’t be easily visible anymore.
Flexbox layout would rather have the flex items overflow the flex container than have the flex items shrink so much they can’t be seen. That’s why the auto
value of minimum size properties is used to calculate a “reasonable minimum” for the flex items. This automatic main size is derived from the content of the flex items.
For example, if your flex item has text in it, a reasonable minimum would be the size of the longest unbreakable word—because you want to be able to read it.
If a flex item is meant to have scrollable content within it, then the auto
value is 0
. If auto
was derived from the content, the flex item would be big enough to fit all of the scrollable content, and there wouldn’t be a need for scrolling anymore.
A flex item becomes a “scroll container” either when it has overflow: scroll
, or when it has overflow: auto
and there’s enough content inside the flex item that scrolling is actually needed to reach it.
To find the automatic minimum size of a flex item, Flexbox layout has to look at all the content inside the flex item. This can take time, especially if you have a lot of content inside the flex item. To speed things up, set an explicit value of the minimum size property instead of relying on auto
.
Note that flex items that have a preferred aspect ratio (like images or any box with aspect-ratio
set) will try to maintain that aspect ratio, and it may make the automatic minimum size bigger.
But if applying the aspect ratio were to make the automatic minimum size smaller than the content size, then it won’t be applied.
If you specified a preferred size smaller than the content size suggestion, that preferred size will be used.
If you have a replaced element (img
, svg
, iframe
), and it has a preferred aspect ratio and a definite cross size, the transferred size suggestion will similarly be used if it’s smaller than the content size suggestion.
If you set a maximum size on the flex item, then the automatic minimum size will respect that.