CSS fit-content: A Useful Keyword That Rarely Comes Up

Ahmad Shadeed has written up the CSS fit-content sizing keyword. It's genuinely useful, though it doesn't show up all that often in day-to-day work. By contrast, min-content gets reached for a lot more — for instance when setting the height of a grid-template-row.

fit-content sits alongside min-content and max-content, and the relationship is close: it simply applies a small heuristic, which Shadeed lays out clearly in a flow chart.

Ahmad Shadeed's flow chat illustrating the way browsers handle the CSS fit-content keyword.
“Use Cases For CSS fit-content” by Ahmad Shadeed

The standout use case in the write-up is sizing a <figure> with fit-content so that it wraps tightly around its <img>. That keeps the image block-level while allowing it to stay at its natural size even when it doesn't fill the parent container.

Tech Report has previously covered PPK's deep dive on fit-content as well. The central takeaway from that piece: the keyword is essentially shorthand for a longer declaration.

.box {
  width: fit-content;

  /* ... is the same as ... */
  width: auto;
  min-width: min-content;
  max-width: max-content;
}

The direct link to Shadeed's article is available from his site.