webroad.online
  1. 1Web
  2. 2HTML
  3. 3CSS
  4. 4JavaScript
  5. 5TypeScript
  6. 6Git
  7. 7Tooling
  8. 8React
  9. 9State management
  10. 10Next.js
  11. 11Forms
  12. 12Data and backend
  13. 13SEO
  14. 14Tailwind CSS
  15. 15Animations
  16. 16Testing
  17. 17Architecture
CSS · Lesson 4 of 8

CSS Grid

Two-dimensional layout: fr, repeat, minmax, auto-fit and areas.

Updated

What CSS Grid is

Grid is the two-dimensional layout system: you define rows and columns on the parent, and the children sit in cells. It's the most powerful layout tool in CSS.

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
}

The fr unit

fr = a fraction of the remaining space. 1fr 2fr → the second column is twice as wide as the first.

Definition Result
200px 1fr a fixed sidebar + content that fills the rest
repeat(3, 1fr) 3 equal columns
1fr auto content + a column as wide as it needs
minmax(200px, 1fr) at least 200px, at most one fraction

A responsive grid without media queries

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
  gap: 1rem;
}

As many columns of at least 16rem as fit; the rest is shared equally. On mobile — one column, on desktop — 3 or 4, automatically.

auto-fit vs auto-fill: with few items, auto-fit stretches them to fill the row; auto-fill keeps empty columns.

Placing children

.featured { grid-column: span 2; }        /* takes 2 columns */
.full     { grid-column: 1 / -1; }        /* from the first line to the last */
.sidebar  { grid-row: 1 / 3; }            /* two rows */

Grid lines are numbered from 1; -1 is the last one.

Named areas

For page layouts, areas are the most readable option:

.layout {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
}
.layout header { grid-area: header; }
.layout aside  { grid-area: sidebar; }

Alignment

Property Aligns
justify-items / align-items the content inside each cell
justify-content / align-content the whole grid inside the container
place-items: center shorthand — centering in the cells

Grid layout types — and when

Layout Definition
equal columns repeat(3, 1fr)
sidebar + content 280px 1fr (like this page)
responsive cards repeat(auto-fit, minmax(16rem, 1fr))
a page with areas grid-template-areas
holy grail (header, 3 columns, footer) areas + minmax

Summary

  • Grid = rows + columns, defined on the parent.
  • fr splits the remaining space; minmax + auto-fit = responsive without media queries.
  • Flex for one axis, grid for two.

Official sources

Exercises

Was this page helpful?

One tap — no account needed.