repeat(): don't repeat yourself
Writing 1fr 1fr 1fr 1fr is tedious. repeat() shortens it:
.gallery {
display: grid;
grid-template-columns: repeat(4, 1fr); /* equals 1fr 1fr 1fr 1fr */
gap: 16px;
}
minmax(): a minimum and a maximum
minmax(min, max) defines a track's size with a floor and a ceiling.
minmax(200px, 1fr) means: "never narrower than 200px, but grow to
distribute the leftover space".
grid-template-columns: minmax(200px, 1fr) 2fr;
The star pattern: cards that rearrange themselves
Combining repeat(), minmax() and the keyword auto-fit you get a
responsive grid without writing a single media query:
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
}
Read the rule like this: "create as many columns of at least 200px as fit; when no more fit, wrap to a new row". Drag the window edge of a product grid and watch the magic: the cards go from 4 to 3, to 2, to 1 column on their own, without a single media query. It is the most used card layout of the modern web, and with this one line you already own it.
auto-fit vs auto-fill
Both create "as many columns as fit", but they differ when there is leftover space and few items:
auto-fill: keeps the empty tracks reserved. The cards keep their minimum width and a gap is left on the right.auto-fit: collapses the empty tracks to 0 and lets the existing items stretch to fill the row.
For card galleries you usually want
auto-fit: it uses the full width. Useauto-fillwhen you want to preserve the grid even with few items.