π What is fit-content()?
fit-content() is a CSS Grid sizing function that allows a grid track (row or column) to size itself based on the content β but only up to a maximum limit. Itβs perfect when you want the track to grow naturally but not exceed a safe size.
π― Syntax
Basic Syntax
fit-content(<max-size>)The grid track will behave like:min(max-content, max-size)meaning it expands to fit content but never exceeds your limit.
π Why Use fit-content()?
- To size columns based on content without overflowing
- To limit how wide text labels or sidebars can grow
- To create adaptive layouts that blend fixed and fluid sizing
- To avoid long items breaking the layout
π§ͺ Basic Example
fit-content in Columns
.container {
display: grid;
grid-template-columns: fit-content(300px) 1fr;
}First column: grows based on content but stops at 300px max. Second column: takes the remaining space.
π Visual Representation

π₯ Example With Labels
Adaptive Label Column
.form {
display: grid;
grid-template-columns: fit-content(200px) 1fr;
gap: 10px;
}Labels grow to fit text but never exceed 200px β clean, readable forms.
π§ How fit-content() Works Internally
| Stage | Description |
|---|---|
| 1οΈβ£ Measure content | Find the size needed for content (max-content size) |
| 2οΈβ£ Compare values | Choose the smallest between max-content and your max-size |
| 3οΈβ£ Final size | Track grows only up to your specified limit |
π§± Practical Use Cases
1οΈβ£ Sidebar With Max Size
Sidebar Layout
.layout {
display: grid;
grid-template-columns: fit-content(260px) 1fr;
}Sidebar grows naturally but never exceeds 260px.
2οΈβ£ Navigation Menus
Menu Example
.menu {
display: grid;
grid-template-columns: repeat(4, fit-content(180px));
}Prevents wide text items from ruining the menu spacing.
π± Responsive Example
Responsive fit-content
.profile {
grid-template-columns: fit-content(150px) 1fr;
}
@media (min-width: 900px) {
.profile {
grid-template-columns: fit-content(250px) 1fr;
}
}On small screens, labels are capped at 150px.
On large screens, they can expand up to 250px.
β οΈ Common Mistakes
- Thinking fit-content() forces a fixed size β it adapts!
- Using it without understanding content size behavior
- Confusing fit-content() with minmax() β they serve different roles
- Applying fit-content() to grid items instead of track definitions
Note
π fit-content() vs minmax()
| Function | Purpose |
|---|---|
| fit-content(300px) | Content-sized track with a maximum limit |
| minmax(150px, 300px) | Strict min & max values regardless of content size |
Note
π₯ Summary
fit-content() is perfect for tracks that should adapt to content but must obey an upper limit to keep your layout stable. It shines in sidebars, form layouts, navigation bars, and anywhere content size varies.
Learn more:MDN Docs π