CSS Grid
Two-dimensional layout
Grid controls rows and columns at the same time, which is perfect for page layouts, galleries and dashboards.
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
gap: 16px;
}
Key ideas
fris a fraction of the free space:2fr 1frgives a wide main area and a narrow sidebar.grid-template-rowssets the row sizes.- Items can span:
grid-column: span 2;orgrid-column: 1 / -1;(full width). place-items: centercentres items in their cells.
The responsive grid without media queries
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
It fits as many 220 px+ columns as there's room for, then stretches them to fill the row.
Named areas: readable page layouts
.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 240px 1fr;
}
header { grid-area: header; }
Flexbox or Grid?
- Flexbox: one direction, with content deciding the sizes (navbars, button groups).
- Grid: two directions, with the layout deciding the sizes (page structure, galleries). They work great together: a grid page with flex inside each card.
Example
<style>
body { font-family: sans-serif; margin: 0; }
.page {
display: grid;
min-height: 100vh;
grid-template-areas:
"header header"
"side main"
"footer footer";
grid-template-columns: 180px 1fr;
grid-template-rows: auto 1fr auto;
gap: 8px;
}
header { grid-area: header; background: #111827; color: white; padding: 12px; }
aside { grid-area: side; background: #eef2ff; padding: 12px; }
main { grid-area: main; padding: 12px; }
footer { grid-area: footer; background: #f3f4f6; padding: 12px; }
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 10px;
}
.gallery div { background: #c7d2fe; height: 80px; border-radius: 8px; }
</style>
<div class="page">
<header>Header</header>
<aside>Sidebar</aside>
<main>
<h2>Gallery</h2>
<div class="gallery"><div></div><div></div><div></div><div></div><div></div></div>
</main>
<footer>Footer</footer>
</div>