HTML & CSS Tip of the Week

min-width: fit-content

Published on


With buttons and other elements where you don’t want the text to wrap, it’s very common to use text-wrap: nowrap.

And, while this works, it’s a little bit heavy-handed, and introduces the potential for overflow, as you can see in this CodePen.

See the Pen default vs nowrap by Kevin (@kevinpowell) on CodePen.

The problem in the example without the text-wrap: nowrap is that the text wrapping looks pretty terrible.

Ideally, the text would only wrap as a last resort.

We can fix this, however, by removing the text-wrap: nowrap, and replacing it with min-inline-size: fit-content.

See the Pen nowrap vs fit-content by Kevin (@kevinpowell) on CodePen.

fit-content is an intrinsic property, which will have an element match the size of it’s content (the text inside of it, in this case) unless there isn’t enough room, in which case it will allow it to wrap.

In other words, it waits until there is no other choice, and it then allows for text wrapping, which is exactly what we want!