Sub topic 3
auto-fit versus auto-fill
Prerequisites
Assume you know basic CSS Grid, semantic HTML, media queries, and units such as rem, px, and %. The key decision here is how empty columns should behave.
`auto-fit` and `auto-fill`
Both keywords work with repeat() and calculate how many tracks can fit:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}auto-fill keeps every column that can fit, even when some columns are empty. auto-fit collapses empty columns, allowing existing items to stretch across the available space.
| Choice | Empty tracks | Common use |
|---|---|---|
| `auto-fill` | Remain available | Preserve a regular column structure |
| `auto-fit` | Collapse | Let a small number of cards expand |
Preventing narrow-screen overflow
A fixed minimum of 200px can overflow a container narrower than 200px. Put min(100%, 200px) inside minmax() so the minimum cannot exceed the container:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr));
gap: 1rem;
}Rearranging named areas
Named areas can change inside a media query. Keep the HTML and grid-area assignments unchanged:
.page {
display: grid;
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
gap: 1rem;
}
@media (min-width: 48rem) {
.page {
grid-template-columns: 14rem 1fr;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
}Combining both layouts
The page can use named areas while main contains an independent auto-fit grid:
.page > main {
grid-area: main;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
gap: 1rem;
}Implicit lines and source order
An area name also creates implicit line names. An area called main creates main-start, main-end, and matching row or column line names. You can use those names for line-based placement, although grid-area: main is usually clearer.
Visual placement does not replace the document structure. Keep elements in a logical source order for screen readers and keyboard users. A sidebar moved visually before main may still be read in its original DOM position.
Exercise
Which keyword collapses empty tracks, and what prevents a 200px card minimum from overflowing?
Show answer
auto-fit collapses empty tracks. minmax(min(100%, 200px), 1fr) limits the minimum to the container width.