Auto-Fill: Creating Responsive Grids
You'll learn how to make CSS Grid automatically create as many columns as will fit in the container, perfect for responsive card layouts.
The Core Idea
The auto-fill keyword works with the repeat() function to tell Grid: "Create as many tracks as possible that fit in this container." Instead of specifying an exact number of columns (like repeat(3, 1fr)), you let the browser calculate how many will fit based on the available space.
Think of it like packing boxes on a shelf: you don't decide "exactly 5 boxes"—you decide "as many boxes as will fit." As the shelf gets wider, more boxes fit automatically.
Basic Syntax
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
gap: 1rem;
}
This creates columns that are 200px wide, and the browser fills the row with as many as will fit. On a wide screen, you might get 6 columns. On a tablet, maybe 3. On mobile, maybe just 1.
Combining with minmax()
The real power comes when you pair auto-fill with minmax():
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
Now each column is at least 250px but can grow to fill available space. The grid automatically wraps to fewer columns when the container narrows, creating a fully responsive layout without media queries.
How It Works
The browser calculates: "How many 250px columns fit?" Then it distributes any extra space using the 1fr maximum, making columns grow equally.
Key Takeaway: repeat(auto-fill, ...) creates a flexible number of tracks that automatically adjust to container width, making truly responsive grids without media queries.