CSS Foundations

Lesson 4 of 6

CSS Grid: Two-Dimensional Layouts

Where Flexbox handles a single row or column, Grid handles rows and columns together, ideal for full page layouts and card galleries.

.page {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  gap: 16px;
  min-height: 100vh;
}
HTML

Defining tracks

  • grid-template-columns: 200px 1fr creates two columns: a fixed 200px sidebar and a flexible column that takes the rest (1fr = "one fraction of the remaining space").
  • repeat() avoids repetition: grid-template-columns: repeat(3, 1fr) creates three equal columns.
  • grid-column: 1 / -1 makes an element span from the first line to the very last, a common trick for a full-width header or footer in a grid.

A responsive card gallery in one line

.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

This creates as many 200px-minimum columns as fit the container, and stretches them evenly to fill any leftover space, all without a single media query.

TIP

A common rule of thumb: reach for Flexbox when you're arranging items in one direction (a toolbar, a list of tags), reach for Grid when you're arranging a whole page or a two-dimensional layout (rows and columns together).

📝 CSS Grid Quiz

Passing score: 70%
  1. 1.What does the "1fr" unit represent in a grid track definition?

  2. 2.CSS Grid can only control columns, not rows.

  3. 3.The property used to turn an element into a grid container is display: ____.