minmax(), auto-fit and auto-fill

Build a responsive card grid that reflows on its own β€” the single most useful grid recipe you'll ever memorize.

This is the recipe that replaced a stack of media queries for most card layouts. Learn it once and reuse it forever:

grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));

Read it as: “make as many columns as fit, each at least 220px wide, and share the leftover space equally.” The grid adds and removes columns entirely on its own as the container changes width.

minmax(MIN, MAX)

It sets a track's lower and upper size. minmax(220px, 1fr) means “never narrower than 220px, but grow to fill a fair share”. The 1fr max is what lets columns stretch to eat the remaining room.

auto-fit vs auto-fill — the classic gotcha

  • auto-fill keeps empty phantom tracks when there aren't enough items, so your cards stay their minimum width and leave gaps.
  • auto-fit collapses those empty tracks to zero, so the existing cards stretch to fill the row.

For most card grids you want auto-fit: a lone card fills the row rather than hugging the left edge.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer uses repeat(auto-fill, minmax(260px, 1fr)) for a product grid that adjusts from 1 column on mobile to 4 on desktop with zero media queries.
  • A designer uses minmax(0, 1fr) instead of 1fr on a grid column that contains long text to prevent the content from overflowing the grid.
  • A developer uses auto-fit versus auto-fill to decide whether the last row of cards should stretch to fill remaining columns or leave them empty.

More examples

auto-fill product grid recipe

The most-used grid recipe: places as many 240px-minimum columns as fit, expanding each to fill remaining space.

Example Β· css
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
}

auto-fit versus auto-fill

Contrasts auto-fill (reserves space for empty slots) with auto-fit (collapses empty slots so items expand to fill the row).

Example Β· css
/* auto-fill: keeps empty column tracks */
.gallery-fill {
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

/* auto-fit: collapses empty tracks so items stretch */
.gallery-fit {
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

minmax(0, 1fr) to prevent overflow

Uses minmax(0, 1fr) so the main column can shrink below its content size, preventing grid overflow from long unbreakable text.

Example Β· css
.layout {
  display: grid;
  /* Prevents long words or code from blowing out the column */
  grid-template-columns: minmax(0, 1fr) 300px;
  gap: 24px;
}
.main  { overflow-wrap: break-word; }
.aside { /* fixed 300px */ }

Discussion

  • Be the first to comment on this lesson.
minmax(), auto-fit and auto-fill β€” CSS | SoundsCode