auto-fit, minmax() & min()

Grids that fit themselves

Lesson 2 of 20 · 10 min · Module 1: Layouts that adapt

Often you want "as many equal columns as fit". CSS grid can work that out for you, so a single rule gives one column on a phone and five on a wide screen.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Create as many columns as fit with auto-fit
  • Set flexible track sizes with minmax()
  • Prevent overflow on tiny screens with min()

The idea

repeat(auto-fit, minmax(200px, 1fr)) creates as many columns as fit, each at least 200px wide, sharing the leftover space equally. Wrapping the minimum in min(100%, 200px) lets a column shrink below 200px when the whole container is narrower than that, so nothing overflows on very small screens.

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr));
  gap: 16px;
}

01Let the browser count

auto-fit asks the browser to place as many columns as fit in the container. In a 768px gallery with a 200px minimum and 16px gaps, three fit; in 1168px, five fit.

02minmax sets a range

minmax(200px, 1fr) means "never narrower than 200px, otherwise share the space equally". The 1fr maximum is what stretches the columns to fill the row exactly.

03auto-fit or auto-fill

With fewer items than columns, auto-fit collapses the empty columns so the items stretch, while auto-fill keeps the empty columns and leaves space at the end of the row.

/* two items in a wide container */
auto-fit:   [   item   ][   item   ]
auto-fill:  [item][item][    ][    ]

Your turn

Give .gallery grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)) and gap: 16px. With this one rule, the six cities show in one column at 390px, three at 800px and five at 1200px.

What the checks look for

  • One column on a 390px phone
  • Three equal columns at 800px
  • Five equal columns at 1200px
  • Cities are 16px apart
  • Nothing overflows a 320px screen
Try it in the editor →

Take this with you

repeat(auto-fit, minmax(…)) builds responsive grids without media queries.

Go a little further

Switch auto-fit to auto-fill and delete four cities to see the difference between the two keywords.

Learn HTML & CSS Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →