CSS Grid: Two-Dimensional Layouts
Where Flexbox handles a single row or column, Grid handles rows and columns together, ideal for full page layouts and card galleries.
.page {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
gap: 16px;
min-height: 100vh;
}
HTML
Defining tracks
grid-template-columns: 200px 1frcreates two columns: a fixed 200px sidebar and a flexible column that takes the rest (1fr= "one fraction of the remaining space").repeat()avoids repetition:grid-template-columns: repeat(3, 1fr)creates three equal columns.grid-column: 1 / -1makes an element span from the first line to the very last, a common trick for a full-width header or footer in a grid.
A responsive card gallery in one line
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
This creates as many 200px-minimum columns as fit the container, and stretches them evenly to fill any leftover space, all without a single media query.
TIP
A common rule of thumb: reach for Flexbox when you're arranging items in one direction (a toolbar, a list of tags), reach for Grid when you're arranging a whole page or a two-dimensional layout (rows and columns together).