CSS Grid has some amazing features that make responsive layouts almost automatic. Instead of writing tons of media queries, you can use grid functions that adapt to available space. Let look at the most powerful responsive techniques.
auto-fill vs auto-fit
Both auto-fill and auto-fit create as many tracks as will fit in
the container. The difference is subtle but important: auto-fill creates empty
tracks even if there are no items to fill them, while auto-fit collapses empty
tracks to zero.
/* Items stretch to fill available space */
.gallery {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
/* Empty tracks stay as fixed-size gaps */
.gallery {
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
In practice, auto-fit with minmax is usually what you want. It
creates a fluid grid where items stretch to fill available space.
The minmax Pattern
minmax(min, max) defines a size range. The track will never be smaller than
min and never larger than max. Combined with auto-fill
or auto-fit, this creates a responsive grid with no media queries.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
}
Each card will be at least 280px wide. When the container gets wider, more cards fit per row. When it gets narrower, fewer cards appear. All automatic.
Combining with Media Queries
Sometimes you still need media queries. For example, changing the number of columns at different breakpoints or adjusting the layout completely for mobile.
.layout {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
}
@media (min-width: 768px) {
.layout {
grid-template-columns: 250px 1fr;
}
}
@media (min-width: 1024px) {
.layout {
grid-template-columns: 250px 1fr 200px;
}
}
This gives you a single column on mobile, a two-column layout on tablets, and a three-column layout on desktop. Clean and predictable.