Stop 05 · Layouts & Responsive DesignTopics · 2/8

CSS Grid

Part of the Web Development Roadmap

In short

When your layout has rows and columns at the same time, like a photo gallery or a full page with sidebar and header, CSS Grid makes it almost boringly easy.

CSS Grid lays content out in two dimensions, rows and columns at once, which is ideal for page layouts, galleries and dashboards.

The jaadu mascot as a cinema usher with a torch points a guest to a seat among neat rows of seats.

Think of it like this

Seats in a cinema hall

A cinema has fixed rows and columns, and every ticket says exactly which seat is yours. Some VIP sofas take two seats. Grid works the same: you draw the rows and columns first, then place items, and some can span more than one cell.

Watch it happen

How auto-fill picks the column count

Width
Fit count
Share space
Place

1/4The gallery is 900px wide. Each column must be at least 200px, with 16px gaps.

The big ideas

What you need to know

Two directions

Flexbox handles one line. Grid handles rows and columns together, which is perfect for page layouts and galleries.

The fr unit

1fr means one share of the free space. 2fr 1fr gives the first column twice as much as the second.

repeat and minmax

repeat(auto-fill, minmax(200px, 1fr)) makes as many columns as fit. Responsive, no media queries needed.

Named areas

grid-template-areas lets you draw the layout with words like "header header" "sidebar main".

See it in code

Walk through the code

css
1/* Responsive gallery */2.gallery {3  display: grid;4  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));5  gap: 1rem;6}7 8/* Page layout with named areas */9.page {10  display: grid;11  grid-template-columns: 240px 1fr;12  grid-template-areas:13    "header header"14    "sidebar main";15}16.page > header { grid-area: header; }

1/4As many columns as fit, each at least 200px, then stretched equally with 1fr.

The gallery shows one column on a phone and five or six on a wide screen, all on its own.

Save yourself the pain

Common mistakes

Oops

Using Grid for a simple row of buttons.

Do this instead

A single row is Flexbox's job. Reach for Grid when you need rows and columns together.

Oops

Setting fixed pixel widths on every column.

Do this instead

Use fr and minmax so columns adapt to the screen.

Your mission

A college fest gallery

~30 min

Quick check

What does grid-template-columns: 1fr 2fr 1fr do?

Go deeper

  1. 1Build a photo gallery with repeat(auto-fill, minmax(200px, 1fr)) so it adapts to any width.
  2. 2Use grid-template-areas to sketch a header, sidebar, main and footer layout.
  3. 3Learn when to pick Grid over Flexbox: two dimensions versus one.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge