Ahmad Shadeed: Use Cases For CSS fit-content

Ahmad Shadeed covers the CSS fit-content sizing keyword. It’s useful! It just doesn’t come up super often. I find myself using min-content a lot more, like when setting up the height of a grid-template-row.

The fit-content keyword is actually closely related to min-content and max-content — it just has a little heuristic it follows that Ahmad nicely illustrates as 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

My favorite use case is covered here: sizing a <figure> with fit-content, so that it neatly wraps around the <img>. That way, even if the image doesn’t fill the parent space, and it can remain block-level.

We also covered PPK’s deep dive on fit-content last year. One of the key takeaways for understanding it is knowing that is it essentially a shorthand way of writing:

.box {
  width: fit-content;

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

To Shared LinkPermalink on CSS-Tricks


Ahmad Shadeed: Use Cases For CSS fit-content originally published on CSS-Tricks. You should get the newsletter.

fit-content and fit-content()

Here’s some hardcore deep-dive CSS nerdery from PPK. If you can wrap your mind around min-content (the smallest an element can be based on the content it contains) and max-content (the largest the content of an element can push it) then it’s just one more little step to understanding fit-content. As PPK says, it’s shorthand for:

.box {
  width: fit-content;

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

Which means the element will be able to resize between the min and max.

My brain always thinks about the only-slightly-convoluted UI situation of centering a horizontal nav that needs it’s own background for some reason. min-content doesn’t work as it smashes it all too narrow. max-content doesn’t work because then it doesn’t allow wrapping. So fit-content is the baby bear porridge.

PPK’s article has a lot more detail about browser quirks and includes really effective interactive figures, so definitely read that — especially if you fancy yourself deeply knowledgable about CSS, as it gets humbling fast when you start getting into the fit-content() function in CSS Grid. Like how does 1fr fit-content(200px) 1fr play out in a template?

1fr min(min(max-content, available-size), max(min-content, 200px)) 1fr

Note: “where available-size is the available width in the grid.” Phew!

Direct Link to ArticlePermalink


The post fit-content and fit-content() appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.