CodePark/ questions / Flexbox
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Flexbox

A flex item contains a long URL or a pre block, and it overflows the container instead of shrinking even though flex-shrink is 1. Why, and how do you fix it?

Flex items have min-width: auto by default, or min-height: auto in a column. For a flex item, that auto resolves to its min-content size. That is the smallest width the content can take without overflowing. It is usually the width of the longest piece that can't break, such as a long word, a URL or a pre line. So the item refuses to shrink below that width.

flex-shrink can only shrink an item down to that minimum. So the item overflows the container.

The fix is min-width: 0 on the item. Another fix is to make the item a scroll container with overflow: hidden, auto or scroll. Those values also make the automatic minimum zero. overflow: clip does not, because it doesn't create a scroll container.

Then choose what the content does:

  • Wrap it with overflow-wrap: anywhere.
  • Scroll it with overflow: auto.
  • Cut it off with text-overflow: ellipsis.

The same problem appears in grid with 1fr tracks. There, the fix is minmax(0, 1fr).

  • Flex items default to min-width: auto.
  • That auto resolves to the min-content size, so the item can't shrink past its longest word or line.
  • Fix it with min-width: 0, or with overflow: hidden, auto or scroll. overflow: clip does not remove the minimum.
  • Then let the content wrap, scroll or truncate.