Responsive Grids

Build grids that reflow automatically.

Syntaxgrid-template-columns: repeat(auto-fit, minmax(120px, 1fr));

Grid can create responsive layouts without media queries by combining repeat(), auto-fit, and minmax().

repeat(auto-fit, minmax(120px, 1fr)) fits as many columns as will fit, each at least 120px wide, sharing leftover space equally.

Example

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

When to use it

  • A developer uses auto-fill with minmax to build a product catalog grid that reflows from 1 to 4 columns as the viewport widens, without a single media query.
  • A designer combines CSS Grid and media queries to shift a three-panel dashboard from side-by-side to stacked layout on mobile.
  • A developer uses grid-template-areas redefined in media queries to rearrange a sidebar layout without changing HTML source order.

More examples

Auto-filling responsive grid

Creates a grid that automatically places as many 240px-minimum columns as fit, expanding each to fill the remaining space.

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

Grid layout with breakpoints

Stacks all panels in a single column on mobile, then expands to a three-column sidebar/main/widget layout on desktop.

Example · css
.dashboard {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}
@media (min-width: 900px) {
  .dashboard {
    grid-template-columns: 240px 1fr 280px;
  }
}

Responsive grid areas at breakpoints

Redefines grid-template-areas in a media query to move the sidebar from below the main content to its right.

Example · css
.page {
  display: grid;
  grid-template-areas: 'main' 'sidebar';
}
@media (min-width: 768px) {
  .page {
    grid-template-columns: 1fr 300px;
    grid-template-areas: 'main sidebar';
  }
}
.main    { grid-area: main; }
.sidebar { grid-area: sidebar; }

Discussion

  • Be the first to comment on this lesson.