A use case for CSS min-content and max-content
- Published at
- Updated at
- Reading time
- 2min
Recently I came across the CSS width
property values min-content
and max-content
. It turns out that you can use min-content
, max-content
and even fit-content
to define an element's width
. The great thing about these values is that they consider the element's content and children.
All three CSS values can be used to define an element's size. max-content
determines a size assuming that there is infinite available space. On the other hand, min-content
defines an element's minimal possible size that does not lead to overflowing content. And lastly, fit-content
is the mix of min-content
and max-content
; if there's enough space, it defines as much size as possible, and otherwise, it falls back to a minimum size that does not include overflowing elements.
If you want to learn more about these values, the #devsheet below gives you a visual explanation.
I haven't heard of these CSS values before and couldn't imagine when these values would be useful. So I asked Twitter to get some answers. As usual, Sven Wolfermann helped me out and sent me a CodePen that showed a use case for min-content
and max-content
.
As you see in the CodePen example, the subline is controlling the overall width of the headline. If you asked me a month ago, I'd probably have said that this is not possible in CSS.
See the Pen CSS Question by @vasilis โ min/max-content by Sven Wolfermann (@maddesigns) on CodePen.
I never had to build a layout like this, but good to know that it's possible. ;)
Edit: Another great use case for fit-content
is when you want to build a centered navigation.
Join 5.5k readers and learn something new every week with Web Weekly.