Today I learned

fit-content

Edit this Post Opens in new tab

If you want to restrict the width of an element to it's content, you may have used display: inline-block or display: inline-flex.

By using this, the element will shrink wrap to the content inside of it.

.container {
  display: inline-block;
}

This is a valid solution to achieve this requirement. But there is a better way to do this. Introducing: width: fit-content. The great thing about width: fit-content is, that it leaves the display property available.

.container {
  width: fit-content;
}

So it's not changing the position of the element in the layout, but it's just a way to restrict the width of the element to it's content. Here is a Codepen, where you can see the usage of it and it's effect:

CodePen - fit-content Opens in new tab

Sources


I hope you enjoyed this post and learned something new. If you have any questions, feel free to reach out to me via Email Opens in new tab.

If you want to support me, you can buy me a coffee. I would be very happy about it!

☕️ Buy me a coffee ☕️

I wish you a wonderful day! Marco