CodeBlanks Logo Icon CodeBlanks

Responsive grid layout

CSS course · Intermediate · Lesson 53/98

Build a responsive grid with auto-fit and minmax.

Responsive grid with auto-fit and minmax

You can build a grid without a fixed column count by setting each column's minimum and maximum width instead. repeat(auto-fit, minmax(200px, 1fr)) lays out columns automatically based on the screen: as many 200 pixel columns as fit.

The grid collapses to one column on narrow screens and opens up on wide ones, with no media query needed.

The minmax() function

The minmax(min, max) function sets both the minimum and maximum width of a column in one go. minmax(150px, 1fr) keeps each column at least 150 pixels and lets it share leftover space when available.

This is smarter than old fixed pixel or pure 1fr values: columns neither collapse too far nor grow needlessly.

auto-fit vs auto-fill

Both values compute how many columns fit; the difference is how they treat empty columns. auto-fit collapses empty columns and leaves room for filled ones; auto-fill keeps empty columns in place.

As a result, with auto-fit the filled columns stretch across the screen; with auto-fill they keep the defined width. Most responsive card grids use auto-fit.

Exercise Build a responsive gallery grid

Make the .gallery grid open as many columns as fit. Each column should be at least 200 pixels and share leftover space (1fr). Write only the grid-template-columns declaration; keep display: grid.

Show example solution
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

Test yourself

  1. What does repeat(auto-fit, minmax(200px, 1fr)) do?

    .gallery {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }
    • A single fixed 200 pixel column
    • Each column 200 pixel fixed, no stretch
    • A fixed two-column grid
    • As many 200 pixel columns as fit
    Show answer

    As many 200 pixel columns as fit — Correct. auto-fit opens as many columns as fit; minmax keeps each at least 200 pixels and shares leftover space.

  2. Keyword for a responsive grid

    .gallery {
      display: grid;
      grid-template-columns: repeat(____, minmax(200px, 1fr));
    }
    Show answer
    .gallery {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }
  3. Match each grid value to its meaning

    minmax(150px, 1fr)
    At least 150px, flexible max
    auto-fit
    Collapse empty columns
    auto-fill
    Keep empty columns
    repeat(3, 1fr)
    Fixed three columns

All lessons in Intermediate