In this short article, we’ll explore some use-cases for CSS fit-content. If you’re new to CSS intrinsic sizing, I wrote about it in detail in this article.

Let’s dive in!

Introduction

The keyword fit-content will make an element width equal to its content based on specific conditions.

Here is a flow chart that shows how the browser deals with it.

It checks if the available is more than max-content, then the width is equal to max-content. If the available space is less than max-content, then the width will be equal to the available space. Finally, if the available space is less than min-content, then the width will be equal to min-content.

Use cases for fit-content

Intrinsic headline

Have you ever needed a way to center a headline and add a custom underline only for the content and not the whole element?

We can do that by wrapping the heading content in a span and then applying the underline on it.

<h1><span>Headline content</span></h1>
h1 span {
  box-shadow: inset 0 -6px 0 0 lightgrey;
}

With fit-content, this is no longer needed.

h1 {
  width: fit-content;
  margin-left: auto;
  margin-right: auto;
  box-shadow: inset 0 -6px 0 0 lightgrey;
}

Demo

Figure and image

Within an article body, we might need to have a <figure> take its content width, and not exceed that if it’s too large.

Using fit-content is perfect for that.

figure {
  width: fit-content;
  margin: 0 auto;
  background: #fff;
  padding: 1rem;
  border-radius: 10px;
}

Demo

Intrinsic Content Block

This is one of my favorites. Within an article body, we want a specific content block to be equal to its content.

In the following figure, we have a “Related article” widget that is equal to its contents.

.article-body .related-widget {
  width: fit-content;
}

Intrinsic Tabs

This is an interesting use-case that I spotted in Google Ads. The idea is that we want the tab element to be clickable only on its content.

In the following figure, notice how the highlighted area represents the tab’s content.

.tab-item {
  flex-grow: 1;
  width: fit-content;
}

I hope you found this article useful. Thank you for reading!