Course contentsShow
← Web Development
Lesson 341 of 2,9826. CSS GridFree lesson

The fit-content() Function

Size tracks to content up to a maximum limit using the fit-content() sizing function.

The fit-content() Function

You'll learn how to size grid tracks that automatically shrink-wrap their content while respecting a maximum size limit.

What is fit-content()?

The fit-content() function is a CSS Grid sizing function that creates tracks which grow to fit their content—but only up to a maximum size you specify. Think of it like putting your content in a flexible container that expands as needed, but stops at a certain point even if more space is available.

It's essentially a shorthand that combines the logic you've learned from min-content, max-content, and minmax().

How It Works

The formula behind fit-content() is:

min(maximum-size, max(minimum-size, content-size))

In practice, this means:

  • The track starts by fitting the content naturally (like max-content)
  • It respects an automatic minimum (preventing collapse)
  • It never exceeds the maximum you specify

Syntax

.grid {
  display: grid;
  grid-template-columns: fit-content(300px) 1fr;
  gap: 20px;
}

Here, the first column will be as wide as its content needs—but will stop growing at 300px, even if more space is available. The remaining space goes to the 1fr column.

Common Use Case

Perfect for sidebars or labels that should adapt to their content without becoming unnecessarily wide:

grid-template-columns: fit-content(200px) 1fr;

The first column shrinks for short content like "Name:" but won't exceed 200px for longer labels.

Key Takeaway: fit-content(max) creates responsive tracks that wrap content naturally while enforcing a maximum size—combining the best of flexible and constrained sizing.