How does CSS Grid work?

CSS Grid is a 2D layout system - define rows and columns on a container, then place children into specific grid cells or let them auto-flow.

CSSGridLayout

Overview

CSS Grid lets you create two-dimensional layouts (rows AND columns simultaneously). Unlike Flexbox which is one-dimensional, Grid gives you precise control over both axes at once. It is ideal for page-level layouts and any design that follows a grid pattern.

Key Points

  • •`display: grid` on the parent creates a grid container.
  • •`grid-template-columns` and `grid-template-rows` define the track sizes.
  • •The `fr` unit represents a fraction of the available space.
  • •`repeat(3, 1fr)` creates three equal-width columns.
  • •`gap` (or `column-gap` / `row-gap`) adds space between tracks.
  • •Items can span multiple columns/rows with `grid-column: 1 / 3` or `grid-column: span 2`.

Examples

Three-column equal grid

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

Classic page layout: sidebar + main + aside

css
.page {
  display: grid;
  grid-template-columns: 200px 1fr 160px; /* sidebar | main | aside */
  grid-template-rows: auto 1fr auto;      /* header | content | footer */
  gap: 1rem;
  min-height: 100vh;
}

Named grid areas (most readable approach)

css
.page {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  grid-template-columns: 200px 1fr;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

The ASCII art in grid-template-areas maps directly to the visual layout.

Responsive auto-fill grid (no media queries needed)

css
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 1.5rem;
}

auto-fill + minmax creates as many columns as fit; they each have a minimum of 240px.

Item spanning multiple columns

css
.featured {
  grid-column: 1 / 3;  /* spans from line 1 to line 3 (2 columns) */
  /* or: */
  grid-column: span 2; /* spans 2 columns from wherever it starts */
}

Pro Tip

Use Grid for the overall page/section layout and Flexbox for the content within each cell. They complement each other: Grid for 2D, Flexbox for 1D alignment within a row or column.