CSS Grid
CSS Grid lays items out in rows and columns at the same time. Where Flexbox handles one direction, Grid handles two, which makes it ideal for page layouts and card galleries.
A basic grid
HTML
<style>
.grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; font-family: system-ui; }
.grid div { background: #eef0ff; border: 2px solid #5a48f5; padding: 18px; border-radius: 8px; text-align: center; }
</style>
<div class="grid">
<div>1</div><div>2</div><div>3</div>
<div>4</div><div>5</div><div>6</div>
</div>grid-template-columns: 1fr 1fr 1fr creates three equal columns. Items fill the grid row by row.
The fr unit
fr means "a fraction of the free space". Mix it with fixed sizes:
HTML
<style>
.g { display: grid; grid-template-columns: 120px 2fr 1fr; gap: 8px; font-family: system-ui; }
.g div { background: #e6f9ff; padding: 12px; border-radius: 6px; }
</style>
<div class="g"><div>120px</div><div>2fr</div><div>1fr</div></div>repeat()
repeat(4, 1fr) is shorthand for 1fr 1fr 1fr 1fr.
Spanning cells
Items can span several columns or rows:
HTML
<style>
.layout { display: grid; grid-template-columns: repeat(4, 1fr); grid-auto-rows: 70px; gap: 8px; font-family: system-ui; }
.layout div { background: #fff4dc; border-radius: 8px; padding: 10px; }
.wide { grid-column: span 2; background: #d9f7ea !important; }
.tall { grid-row: span 2; background: #eef0ff !important; }
</style>
<div class="layout">
<div class="wide">span 2 columns</div><div class="tall">span 2 rows</div><div>c</div>
<div>d</div><div>e</div><div>f</div>
</div>A whole page layout
grid-template-areas lets you draw the layout with names:
HTML
<style>
.page {
display: grid;
grid-template-columns: 160px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
gap: 8px; height: 260px; font-family: system-ui;
}
.page > * { padding: 12px; border-radius: 8px; background: #eef0ff; }
header { grid-area: header; } aside { grid-area: sidebar; } main { grid-area: main; background: #fff !important; border: 1px solid #ccd; } footer { grid-area: footer; }
</style>
<div class="page">
<header>Header</header><aside>Sidebar</aside><main>Main content</main><footer>Footer</footer>
</div>Responsive without media queries
This one line makes as many columns as fit, each at least 140px wide:
HTML
<style>
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; font-family: system-ui; }
.cards div { background: #e6f9ff; padding: 22px; border-radius: 10px; text-align: center; }
</style>
<div class="cards">
<div>Python</div><div>SQL</div><div>React</div><div>Java</div><div>CSS</div>
</div>Open it in the playground and resize the preview to watch the columns rearrange.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.