Grid Tracks
Overview
When building a Grid, you define Tracks (the actual rows and columns). Hardcoding pixels (grid-template-columns: 200px 200px) is terrible for responsive design. CSS Grid introduced an incredibly powerful new unit specifically for Grid: the fr (Fractional Unit). It dynamically calculates the leftover free space in the container and distributes it proportionally, completely eliminating the need for complex calc() math.
Syntax
/* --- The 'fr' (Fraction) Unit --- */
.grid {
display: grid;
/*
Column 1 gets 1 share.
Column 2 gets 2 shares (Twice as wide!).
Column 3 gets 1 share.
*/
grid-template-columns: 1fr 2fr 1fr;
}
/* --- The repeat() Function --- */
.gallery {
display: grid;
/* Instead of writing '1fr 1fr 1fr 1fr 1fr 1fr' */
grid-template-columns: repeat(6, 1fr);
}
/* --- Mixing Units! --- */
.dashboard {
display: grid;
/* Left sidebar is exactly 250px.
Right sidebar is exactly 20%.
The middle column mathematically absorbs EVERY leftover pixel! */
grid-template-columns: 250px 1fr 20%;
}Common Pitfalls
- Using
%(percentages) instead offr. If you usegrid-template-columns: 33% 33% 33%and add agap: 20px, the grid will explode out of its container and cause a horizontal scrollbar. Thefrunit mathematically calculates the space AFTER the gaps have been subtracted, making it bulletproof. - Assuming
1frmeans 'shrink to 0'. By default,1frhas an implicitmin-width: auto, meaning it will refuse to shrink smaller than the longest word or image inside of it. If an image blows out your grid, change it tominmax(0, 1fr)to force it to shrink.
Interview Questions
fr unit instead of percentages (%) when defining CSS Grid columns?Because fr natively accounts for the CSS gap property. It subtracts the gap gutters first, then divides the remaining space. Percentages do not, leading to immediate overflow issues.
Real-World Example
Using the repeat() function to create a clean, 12-column bootstrap-style grid system natively.
.container-12 {
display: grid;
/* Instantly creates 12 perfectly equal, fluid columns */
grid-template-columns: repeat(12, 1fr);
gap: 16px;
}Check Your Knowledge
Test your understanding of Grid Tracks with these quick questions.