Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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.

min-content, max-content, fix-content devsheet

min-content and max-content – a combination to create smart layouts

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.

min-content max-content use case

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.

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 18 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles