CSS Grid Responsive Layout Snippet
A responsive card grid that fills as many columns as fit and never produces an awkward last row is a one-line CSS Grid trick. This snippet covers the canonical `auto-fill` plus `minmax` recipe, the `auto-fit` variant that collapses empty tracks, and a row-spanning variant for masonry-like layouts. No media queries, no JavaScript.
460 views
15
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1rem;
}
.card {
background: white;
padding: 1rem;
border-radius: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}repeat(auto-fill, minmax(240px, 1fr)) tells the grid to lay out as many tracks as fit at a minimum of 240px and let each one stretch up to 1fr. The result is a fluid grid that reflows from one column on a phone to four or more on a wide monitor without a single media query. gap handles the spacing instead of margins, which keeps the math simple and avoids extra spacing at the container edges. This is the recipe to memorise; everything else in this snippet is a variation on it.
.card-grid-fit {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1rem;
}auto-fit differs from auto-fill in one subtle but important way: when the children do not fill every track, auto-fit collapses the empty tracks so the existing children stretch to fill the row, while auto-fill keeps the empty tracks reserved. Use auto-fit when you want a single child to stretch to full width on small screens, and use auto-fill when you want a consistent column rhythm regardless of how many items there are. Most card grids look better with auto-fit; tabular layouts often want auto-fill.
.masonry {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
grid-auto-rows: 8px;
gap: 1rem;
}
.masonry > .item {
grid-row: span 30;
}
.masonry > .item.tall {
grid-row: span 48;
}
.masonry > .item.short {
grid-row: span 18;
}True CSS masonry is still gated behind a feature flag in most browsers, but a row-span trick approximates it well enough for image galleries. Setting grid-auto-rows to a small unit (8px) and giving each child a grid-row: span N based on its desired height produces a packed layout without jagged column breaks. The number of spans per item can be calculated server-side or set via inline styles after measuring images. The trade-off versus real masonry is gaps between rows, which the small auto-row mostly hides.
