Flexboxes Really Like `min-width`
CSS Flexboxes are one of these concepts that look so appealing if you’ve struggled in the past with implementing the types of layouts they were created to simplify, but in practice, there’s no shortage of opportunities to code things that don’t work as expected.
Recently, I learned that if a flexbox item or container isn’t behaving as expected in terms of resize behaviour, there’s probably a flex item missing a min-width: 0
somewhere between the misbehaving item and the highest-level flexbox container of the HTML document.
More specifically, in order for a flexbox to shrink appropriately, all flex items in row-orientation flexboxes all the way to the root of the document need to have a min-width
property set. Most of the time, this will be set to 0
, but of course, other values may be fine too. But it’s important to set it, because otherwise the default value for the min-width
property of a flex item is min-content
. The layout algorithm then goes down into the child elements and calculates their desired value, and if one of them would rather be wide, that result will bubble up to the flex item without the min-width
property and will make it large.
Case in point, I was struggling with an application-type layout where the window is a sidebar and a main content area, which itself contains a filter view, a table view and a third view to show details of the selected element in the table. The table itself was just a flexbox with rows inside, each of these its own vertical flexbox containing a left-aligned text and a right-aligned money amount. When I wanted to make the text stop wrapping and show an ellipsis character instead, the whole table view suddenly became larger than the window. I figured out that the longest item description in the table would decide the width of the entire table.
The culprit? The main area element all the way at the top, just below the BODY
tag, had no min-width
set, and was now being sized according to the longest line in the table, 8 elements deep.
It seems setting overflow: hidden
is equivalent to min-width: 0
for this purpose, though I’m not too sure what the differences might be there, if any.