Sub topic 12
Responsive grids with auto-fill and auto-fit
This chapter assumes you can write grid-template-columns, use fr units and repeat() with a fixed count, and use gap. It also assumes you know what minmax() does. Here you combine those pieces so the number of columns adapts to the container width, without media queries.
The problem with a fixed column count
repeat(4, 1fr) always makes four columns. On a narrow screen each column becomes too thin to read. The usual fix is a media query that changes the count at set breakpoints. That works, but you must pick the breakpoints yourself, and they depend on the viewport, not on the space the grid actually has.
Grid can instead calculate the column count from the available width. You give repeat() a keyword, auto-fill or auto-fit, in place of a number.
The core pattern
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
}Read it from the inside out:
minmax(240px, 1fr)describes one track. It is never narrower than 240px. It may grow to an equal share of the free space.repeat(auto-fit, ...)adds as many of those tracks as fit in the container.- The tracks then stretch (because of
1fr) to fill the row.
Suppose the container is 1000px wide and gap is 1.5rem (24px). Each added column costs its width plus one gap. Four columns need 4 × 240 + 3 × 24 = 1032px, which does not fit. Three need 3 × 240 + 2 × 24 = 768px, which fits. So the grid has three columns, and each stretches to (1000 − 48) / 3, about 317px.
The browser counts gaps when it decides how many tracks fit. You do not need to subtract them yourself.
How auto-fill and auto-fit differ
Both keywords create as many tracks as fit. They differ only when there are fewer items than tracks. Then some tracks are empty.
auto-fillkeeps the empty tracks. They take up space, so the items stay at their normal size and leave blank space at the end of the row.auto-fitcollapses empty tracks to zero width. The remaining tracks can then grow with1frand fill the whole row.
.fill { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
.fit { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }Take a 1000px container and two items. Five 200px tracks would fit, ignoring gaps. With auto-fill, five tracks exist, each 200px, and two hold items. The items are 200px wide with empty space to their right. With auto-fit, the three empty tracks collapse. The two items share the row and each becomes about 500px wide.
When there are enough items to fill every track, the two keywords give identical results. The difference shows up only on a partly filled row.
Which one to choose
- Use
auto-fitwhen items should stretch to use the full width, as in a card list with an unknown number of cards. - Use
auto-fillwhen you want a consistent column size regardless of item count, so a single card does not become huge. It also keeps columns aligned with other grids on the page that use the same track size.
Why minmax() is required
auto-fill and auto-fit need a definite track size to know how many tracks fit. repeat(auto-fit, 1fr) is invalid, because 1fr has no minimum the browser can use to count. It needs a fixed minimum, which minmax(240px, 1fr) supplies. A plain length such as repeat(auto-fill, 200px) is also valid, but the tracks do not stretch, and any leftover space remains at the end of the row.
The repeat count must also be resolvable from the container size. If the grid container has no definite width, the browser works from the available space in its parent block, which is usually what you want.
Avoiding overflow on narrow screens
There is a well-known edge case. If the minimum is larger than the container, the track cannot shrink, and the grid overflows horizontally. With minmax(240px, 1fr) in a 200px container, the single column stays 240px wide.
The fix is to cap the minimum with min():
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(240px, 100%), 1fr));
gap: 1.5rem;
}min(240px, 100%) resolves to 240px when the container is wide enough, and to the container width when it is narrower. The grid then falls back to one full-width column instead of overflowing.
Mixing fixed and automatic columns
repeat() with an auto keyword may be combined with other tracks, but you may use only one auto-repeat per track list. A common use is a fixed sidebar plus a flexible set of columns:
.layout {
display: grid;
grid-template-columns: 200px repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
}You can also use auto-fill with a limited range by capping the maximum with max() or by constraining the container's width:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
max-width: 1200px;
margin-inline: auto;
}Here the container never grows past 1200px, so the grid never creates more than four columns of 240px or more (with no gap).
Limiting the number of columns
Auto-repeat gives you a minimum width but no maximum column count. On a very wide screen you may get seven or eight thin columns. Two common approaches:
- Set
max-widthon the container, as shown above. - Compute the minimum from the desired maximum count. This keeps at most three columns:
.cards {
--gap: 1rem;
--max-cols: 3;
--min-col: 220px;
display: grid;
gap: var(--gap);
grid-template-columns: repeat(
auto-fit,
minmax(
max(var(--min-col), calc((100% - (var(--max-cols) - 1) * var(--gap)) / var(--max-cols))),
1fr
)
);
}The max() takes the larger of the fixed minimum and the width a column would have if exactly three columns shared the row. Because that second value is never exceeded by the minimum, a fourth column cannot fit.
Combining with media queries
Auto-repeat does not replace media queries entirely. It handles the count of equal columns well. It does not handle layout changes where the structure differs, such as moving a sidebar below the content. For those, use a media query to redefine grid-template-areas or the track list.
.page {
display: grid;
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
}
@media (min-width: 48rem) {
.page {
grid-template-columns: 220px 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
}A practical split: use auto-repeat inside regions (a card list in main), and media queries for the overall page structure.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Declaration is ignored | `repeat(auto-fit, 1fr)` has no fixed minimum | Use `minmax(Npx, 1fr)` |
| Items do not stretch when there are few of them | `auto-fill` keeps empty tracks | Switch to `auto-fit` |
| Horizontal scrollbar on small screens | Minimum is wider than the container | Use `minmax(min(240px, 100%), 1fr)` |
| Too many thin columns on wide screens | No upper limit on count | Add `max-width` or the `max()` formula |
| Declaration is ignored | Two auto-repeats in one list | Keep only one |
Summary of the decision
- Need equal flexible columns that adapt to width:
repeat(auto-fit, minmax(min, 1fr)). - Need columns to stay a consistent size even with few items: use
auto-fill. - Need a fixed maximum count: cap with
max-widthor themax()formula. - Need a different structure at different sizes: use a media query with
grid-template-areas.
Exercise
A container is 900px wide with gap: 20px and grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)). It holds two items. How many tracks does the grid create, how wide is each, and what changes if you switch to auto-fit?
Show answer
Four tracks need 4 × 200 + 3 × 20 = 860px, which fits. Five need 5 × 200 + 4 × 20 = 1080px, which does not. So there are four tracks, each (900 − 60) / 4 = 210px wide. With auto-fill, the two items are 210px wide and the other two tracks stay empty. With auto-fit, the two empty tracks collapse to zero, and the two items share the row at (900 − 20) / 2 = 440px each. The gaps next to collapsed tracks collapse too.
Exercise
Write a grid-template-columns value that makes cards at least 180px wide, stretches them to fill the row, stretches them even when there are only one or two cards, and does not overflow a 150px-wide container.
Show answer
grid-template-columns: repeat(auto-fit, minmax(min(180px, 100%), 1fr));