Auto-Fit Grids
Overview
Responsive web design usually involves writing dozens of Media Queries to change the number of columns on a grid (1 col on mobile, 2 on tablet, 4 on desktop). CSS Grid introduced a legendary combination: repeat(auto-fit, minmax(...)). This single line of CSS creates an infinitely fluid, infinitely wrapping grid layout without writing a single Media Query. It is the holy grail of automated responsiveness.
Syntax
/* The Holy Grail of Responsive Grids (Zero Media Queries!) */
.card-grid {
display: grid;
gap: 20px;
/*
auto-fit: Creates as many columns as will physically fit.
minmax(250px, 1fr):
- The columns can NEVER shrink below 250px (Floor).
- If there is extra space, they stretch to fill it equally (1fr).
*/
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}Common Pitfalls
- Confusing
auto-fitwithauto-fill. If you have a massive screen and only 2 cards...auto-fillwill create empty, invisible 'ghost' columns to fill the space, leaving the 2 cards small on the left.auto-fitwill collapse the empty columns and allow the 2 cards to stretch massively to fill the whole screen. You almost always wantauto-fit. - Setting the
minmax()minimum too high (e.g., 400px). If a user is on an iPhone SE (320px screen width), the column literally cannot shrink below 400px, causing terrible horizontal overflow. Always ensure your minimum is mobile-safe (around 250px-300px).
Interview Questions
repeat(auto-fit, minmax(300px, 1fr)) behaves when the screen shrinks from Desktop to Mobile.On desktop, it might fit four 300px columns. As the screen shrinks, the columns shrink. When they hit exactly 300px and can no longer fit, the grid forcefully 'breaks' the last column down to the next row, and the remaining three instantly expand (1fr) to fill the space. This process repeats until mobile, where it becomes one single column.
Real-World Example
A bulletproof E-commerce product grid that perfectly scales from a 4K TV down to an Apple Watch.
.product-grid {
display: grid;
/*
Min: 280px (Safe for phones)
Max: 1fr (Fills all empty space)
Wrap: Automatic based on screen size!
*/
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}Check Your Knowledge
Test your understanding of Auto-Fit Grids with these quick questions.