min-content, max-content, fit-content: the sizing keywords that solve flex overflow

· Tags: flexbox, sizing

A Stockholm agency once paid me to debug a flex layout that “broke on Finnish.” The real bug was simpler: a single unbreakable word like lentokonesuihkuturbiinimoottoriapumekaanikkoaliupseerioppilas refused to shrink below its own length, and the flex item burst the container. The fix was three keywords most CSS developers have read about and never used.

The implicit min-width

Flex items have an automatic minimum size equal to their min-content. This is defined in CSS Flexible Box Layout Module Level 1 § 4.5, “Automatic Minimum Size of Flex Items,” which reads: “To provide a more reasonable default minimum size for flex items, this specification introduces a new auto value as the initial value of min-width and min-height.” That default is why a flex child with flex: 1 still blows out on a long URL.

The three keywords

min-content is the narrowest the content can be without overflow — roughly the width of the longest unbreakable token. max-content is the width with no wrapping at all. fit-content(<length>) clamps between the two: it is max-content capped at the argument. Tab Atkins and Elika Etemad's CSS Intrinsic & Extrinsic Sizing Module Level 3 (W3C Working Draft) is the normative definition.

The fix for the Finnish bug

Set min-width: 0 on the flex child, and it will shrink below its min-content — producing either ellipsis truncation (with overflow: hidden; text-overflow: ellipsis) or word-break. This is the most common single-line fix in production flex code and is documented in Rachel Andrew's CSS Working Group blog post “Min and max sizing in CSS,” 12 November 2019.

When to use fit-content

For flex items that should grow with content but never exceed a ceiling — tags, chips, inline badges — width: fit-content is cleaner than the old display: inline-block hack. Ahmad Shadeed's Debugging CSS, self-published 2021, ch. 6, has a thorough worked example.

The mental model

Flex sizing decides three things per item: the base size (from flex-basis), the minimum (from min-width, defaulting to auto which is min-content), and the maximum (from max-width). Overflow happens when the minimum exceeds the container. Name the minimum explicitly, and the browser has room to negotiate.

Related

Get FlexFrog on the App Store