CSS Grid Recipes: auto-fit, minmax and Subgrid
CSS Grid handles two-dimensional layout: rows and columns. These recipes cover most real-world layouts.
Responsive cards without media queries
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr));
gap: 1.5rem;
}
Columns are at least 260px and stretch to fill the row; the number of columns changes with the available width. min(260px, 100%) prevents overflow on very small screens.
Page layout with named areas
.page {
display: grid;
grid-template:
"header header" auto
"sidebar main" 1fr
"footer footer" auto
/ 240px 1fr;
min-height: 100dvh;
}
header { grid-area: header; }
aside { grid-area: sidebar; }
main { grid-area: main; }
footer { grid-area: footer; }
@media (max-width: 800px) {
.page {
grid-template: "header" auto "main" 1fr "sidebar" auto "footer" auto / 1fr;
}
}
Subgrid: align content across cards
Cards in a row often have titles of different lengths, so their buttons don't line up. With subgrid, each card uses the parent grid's rows:
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
}
.card {
display: grid;
grid-row: span 3; /* title, text, button */
grid-template-rows: subgrid; /* share the parent's row sizes */
}
Centering anything
.center {
display: grid;
place-items: center;
}
Grid or Flexbox?
- Grid when you control both rows and columns (page layouts, card grids).
- Flexbox for a single row or column whose items size to their content (toolbars, tags, nav links).
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.