Lesson 8 of 18

CSS Grid 🍴

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

What You'll Learn

  • Create two-dimensional grid layouts
  • Use grid-template-columns and grid-template-rows
  • Build a responsive card grid

Grid vs Flexbox

Flexbox is great for one-dimensional layouts (a row OR a column). CSS Grid is designed for two-dimensional layouts (rows AND columns together). Think of it like a spreadsheet.

CSS
.grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;  /* 3 equal columns */
  grid-template-rows: auto;             /* rows size to content */
  gap: 1.5rem;                          /* space between cells */
}

The fr unit means "fraction of available space." 1fr 1fr 1fr = three equal columns.

Shorthand with repeat()

CSS
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);  /* same as 1fr 1fr 1fr */
  gap: 2rem;
}

/* Make it responsive: */
.grid-responsive {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
}
💡
Auto-Fit + Minmax

grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)) is the magic line for responsive grids. It automatically adjusts how many columns fit based on screen width!

Spanning Multiple Cells

CSS
.featured-card {
  grid-column: span 2;  /* takes up 2 column slots */
}
.full-width {
  grid-column: 1 / -1;  /* spans ALL columns */
}
🍴">Course Card Grid

Create 6 card divs. Put them in a grid container with repeat(auto-fit, minmax(280px, 1fr)) and gap: 1.5rem. Style each card with padding, border, border-radius, and a background color. Resize your browser window and watch the grid reflow!

Quick Check

What does 1fr mean in CSS Grid?

A1 pixel
BOne font unit
COne fraction of available space

What does grid-column: span 2 do?

ASkips 2 columns
BMakes the element span across 2 columns
CCreates 2 new columns

What is the key advantage of CSS Grid over Flexbox?

ACSS Grid is faster to load
BCSS Grid handles 2D layouts (rows AND columns)
CCSS Grid does not need a wrapper element