Two-dimensional layouts made simple
Add this to any container to enable grid:
display: grid;
That's it. Everything inside becomes a grid item.
Grid works in TWO dimensions — rows AND columns at the same time. Use it for page layouts, image galleries, and anything that needs alignment in both directions.
Apply these to the parent element (the grid container)
/* Three equal columns */
grid-template-columns: 1fr 1fr 1fr;
/* Fixed + flexible + fixed */
grid-template-columns: 200px 1fr 100px;
/* Repeat shorthand */
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 50px 100px 50px;
grid-template-rows: auto 1fr auto;
gap: 20px; /* All gaps */
gap: 10px 20px; /* Row gap, column gap */
row-gap: 10px; /* Just rows */
column-gap: 20px; /* Just columns */
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
Apply these to child elements (grid items)
/* Span 2 columns */
grid-column: span 2;
/* Span 2 rows */
grid-row: span 2;
/* Start at line 1, end at line 3 */
grid-column: 1 / 3;
/* In your container: */
grid-template-areas: "header header" "sidebar main";
/* On the item: */
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
justify-self: start; /* Horizontal: start|end|center|stretch */
align-self: center; /* Vertical: start|end|center|stretch */
/* Shorthand */
place-self: center center;
/* Columns auto-adjust, minimum 200px each */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
/* auto-fit: collapses empty tracks */
/* auto-fill: keeps empty tracks */
/* Column is at least 150px, at most 1fr */
grid-template-columns: minmax(150px, 1fr) 2fr;
/* Row is at least 100px, grows to fit content */
grid-template-rows: minmax(100px, auto);
.page {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
}
/* Cards auto-wrap, no media queries needed */
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
/* Make featured image span 2x2 */
.featured {
grid-column: span 2;
grid-row: span 2;
}
.center-everything {
display: grid;
place-items: center;
min-height: 100vh;
}
/* That's it. Perfectly centered. */
fr means "fraction of available space." 1fr 2fr means the second column gets twice as much space as the first. It's like flexbox's flex-grow but for grid.
Use Grid when: You need rows AND columns aligned. Page layouts, galleries, forms.
Use Flexbox when: You need ONE direction. Navigation bars, button groups, centering.