CSS Tutorial · CSS Layout · Lesson 13 of 19
CSS Grid
Two-dimensional layouts with grid-template-columns, fr units, areas and auto-fit.
Grid containers
display: grid defines rows and columns:
<style>
.grid { display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 8px; font: 14px system-ui; }
.grid div { background: #ede9fe; padding: 12px; border-radius: 6px; }
.wide { grid-column: span 2; background: #c4b5fd !important; }
</style>
<div class="grid">
<div>2fr</div><div>1fr</div><div>1fr</div>
<div class="wide">spans 2 columns</div><div>1fr</div>
</div>
frmeans "a fraction of the free space".repeat(3, 1fr)is three equal columns.gapspaces rows and columns.- Items can span tracks:
grid-column: span 2.
Responsive without media queries
repeat(auto-fit, minmax(150px, 1fr)) fits as many columns as possible, each at least 150px wide — resize the window to watch it reflow:
<style>
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; font: 14px system-ui; }
.cards div { background: #ecfeff; border: 1px solid #67e8f9; border-radius: 8px; padding: 16px; }
</style>
<div class="cards">
<div>Card 1</div><div>Card 2</div><div>Card 3</div><div>Card 4</div><div>Card 5</div>
</div>
Template areas
Name regions and place them visually:
<style>
.page {
display: grid;
grid-template-columns: 140px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"nav main"
"footer footer";
gap: 6px; height: 220px; font: 14px system-ui;
}
.page > * { padding: 8px; border-radius: 6px; }
header { grid-area: header; background: #1e3a8a; color: white; }
nav { grid-area: nav; background: #e2e8f0; }
main { grid-area: main; background: #f8fafc; border: 1px solid #e2e8f0; }
footer { grid-area: footer; background: #e2e8f0; }
</style>
<div class="page">
<header>Header</header><nav>Nav</nav><main>Main</main><footer>Footer</footer>
</div>
Flexbox or grid? Flexbox for one direction (a row of buttons, a nav bar); grid for two-dimensional page and card layouts.
Test yourself
What does 1fr mean in a grid track?
1 pixelOne fraction of the free spaceFull rowFirst row
Show answer
Answer: One fraction of the free space