Responsive Grid Layout with CSS Grid
A responsive card grid in one line of CSS, no media queries.
A common layout is a grid of cards that shows four columns on a big screen, two on a tablet and one on a phone. You could write a media query for every breakpoint, but CSS Grid can handle it on its own.
TL;DR grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) creates as
many columns as will fit, each at least 250px wide.
The One Line Grid
Here's the whole thing:
<div class="grid"><div class="card">One</div><div class="card">Two</div><div class="card">Three</div><div class="card">Four</div></div>
.grid {display: grid;grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));gap: 20px;}
Resize the browser and the cards wrap onto new rows by themselves, without any media queries.
How It Works
There are a few pieces working together here:
repeat()repeats a column definitionauto-fittells the browser to fit as many columns as it canminmax(250px, 1fr)makes each column at least 250px and at most one equal share of the leftover space
So on a 1100px wide container you get four columns, and as it shrinks below each multiple of 250px a column drops onto the next row. At phone width you're left with one column that fills the screen.
auto-fit vs auto-fill
You may also see auto-fill, which looks almost the same. The difference only
shows up when there aren't enough items to fill a row:
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
auto-fillkeeps the empty column tracks, so your items stay 250px wideauto-fitcollapses the empty tracks, so your items stretch to fill the row
If you have two cards on a wide screen, auto-fit makes them each half the
width, and auto-fill leaves them small on the left. Most of the time
auto-fit is what you want.
Avoiding Overflow on Small Screens
If the container gets narrower than 250px, the columns will overflow. Wrapping
the minimum in min() fixes that, but browser support for it is still landing,
so a small media query is the safer option for now:
@media (max-width: 300px) {.grid {grid-template-columns: 1fr;}}
gap vs grid-gap
You might see grid-gap in older code. It was renamed to gap, and current
browsers support both. If you need to support older versions of Safari, add
both:
.grid {grid-gap: 20px;gap: 20px;}
Pretty nifty for one line of CSS.
Have some feedback on this post? .