🌱BeginnerCSS Grid

CSS Grid Basics

Create two-dimensional layouts with CSS Grid using grid-template-columns, grid-template-rows, and gap.

Overview

CSS Grid is a two-dimensional layout system it works with both rows and columns simultaneously. While Flexbox is great for one-dimensional layouts (a row of buttons, a nav), Grid excels at page-level layouts and card grids. To create a grid, set `display: grid` on the container, then define columns and rows: - `grid-template-columns` defines the column widths - `grid-template-rows` defines the row heights (often let the browser calculate automatically) - `gap` spacing between cells - `fr` unit fractional unit: distributes remaining space proportionally The `repeat()` function avoids repetition: `repeat(3, 1fr)` is the same as `1fr 1fr 1fr`. The `auto-fill` and `auto-fit` keywords combined with `minmax()` create responsive grids that automatically adjust the number of columns.

Key Points

  • •display: grid on parent turns children into grid items
  • •grid-template-columns: 1fr 1fr 1fr creates 3 equal-width columns
  • •fr unit: fraction of available space after fixed values are subtracted
  • •repeat(3, 1fr) is shorthand for 1fr 1fr 1fr
  • •gap adds space between rows and columns
  • •repeat(auto-fill, minmax(250px, 1fr)) creates a responsive grid automatically

Examples

Basic 3-column grid

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;  /* three equal columns */
  gap: 24px;
}

/* Or using repeat */
.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
}

Grid items automatically flow into cells. No need to specify which cell each item goes in.

Mixed column sizes

.page-layout {
  display: grid;
  grid-template-columns: 250px 1fr;   /* sidebar + main */
  gap: 32px;
}

/* Three unequal columns */
.dashboard {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 16px;
}

Responsive auto-fill grid

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

/* Columns auto-adjust:
   - Wide screen: 4 columns (each ~280px+)
   - Medium screen: 3 columns
   - Narrow screen: 1–2 columns
   No media queries needed! */

This is the most powerful responsive grid pattern in CSS.

Common Mistakes

  • Confusing fr with % fr distributes remaining space after fixed-size items; % is always relative to the container
  • Forgetting gap and using margin hacks instead
  • Not using auto-fill/auto-fit creating fixed column counts that break on small screens

Note

For responsive card grids, always start with "repeat(auto-fill, minmax(Xpx, 1fr))" where X is the minimum card width you want. This gives you a fully responsive layout with no media queries.

Exercises

Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What does the "fr" unit represent in CSS Grid?