fit-content and fit-content()

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

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 →