Articles /
CSS Grid fundamentals
CSS Grid gives you two-dimensional layout power. Define rows and columns, place items explicitly or let the browser auto-place them.
Defining tracks
Use grid-template-columns and grid-template-rows to create tracks. The fr unit distributes free space proportionally.
.page {
display: grid;
grid-template-columns: 16rem 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100dvh;
gap: 1.5rem;
}
Template areas
Name grid regions with grid-template-areas for a visual, readable layout definition.
.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 14rem 1fr;
grid-template-rows: auto 1fr auto;
}
.page-header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.page-footer { grid-area: footer; }
minmax() and responsive tracks
minmax() sets a minimum and maximum size for a track. Pair it with auto-fill or auto-fit for fluid grids without media queries.
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr));
gap: 1.5rem;
}
auto-fill— creates as many tracks as fit, even if empty.auto-fit— collapses empty tracks so items stretch to fill the row.
Explicit placement
Place items by line number or span. Line numbers start at 1, and negative numbers count from the end.
.feature-card {
grid-column: 1 / -1; /* full width */
}
.hero-image {
grid-column: 2 / span 2;
grid-row: 1 / 3;
}
Alignment in Grid
Grid supports the same alignment properties as Flexbox, plus place-items and place-content shorthands.
.center-grid {
display: grid;
place-items: center; /* center both axes */
min-height: 50dvh;
background: oklch(95% 0.02 260);
}
.stretch-grid {
align-items: stretch;
justify-content: space-between;
}
Subgrid
subgrid lets a nested grid inherit track sizes from its parent, keeping child items aligned across siblings.
.card {
display: grid;
grid-row: span 3;
grid-template-rows: subgrid; /* aligns heading, body, footer across cards */
}