DevPath · Learn to code ESPTEN

CSS Grid

Responsive without media queries: auto-fit and minmax

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:

For card galleries you usually want auto-fit: it uses the full width. Use auto-fill when you want to preserve the grid even with few items.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Placing items: lines, span and areasView the module →