Kodokon kodokon.com

Grid: columns, rows, areas

Build galleries and complete page layouts with CSS Grid's columns, rows, and named areas.

9 min · 3 questions

Open this lesson in Kodokon

Flexbox aligns along one axis; Grid controls both at once. As soon as your mockup looks like a table - photo gallery, dashboard, full page with header, sidebar, and footer - Grid is the right tool. The container defines the structure in columns and rows, and the children place themselves automatically or exactly where you choose.

CSS
.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}
A gallery with three equal columns, spaced 1rem apart.

The fr (fraction) unit shares out the available space: 1fr 2fr creates two columns where the second is twice as wide. Unlike percentages, fr accounts for the gap without any calculation on your part. To highlight an element, make it span several tracks with grid-column and grid-row.

CSS
.featured {
  grid-column: span 2;
  grid-row: span 2;
}
The featured card spans 2 columns and 2 rows.

For a full page, grid-template-areas lets you draw the mockup directly in the CSS. Each string represents one row of the grid, each word a named area. A child then places itself with grid-area. The result reads like an architect's blueprint: it's the most readable method for a page layout.

CSS
.page {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}

.site-header { grid-area: header; }
.site-nav { grid-area: sidebar; }
.site-main { grid-area: main; }
.site-footer { grid-area: footer; }
A complete page layout, readable like a blueprint.

Knowledge check

Make sure you remember the key points of this lesson.

  1. What does the fr unit represent in grid-template-columns: 1fr 2fr?
    • A fraction of the container's available space
    • A percentage of the screen width
    • A fixed size expressed in pixels
  2. Which declaration creates three columns of equal width?
    • grid-template-columns: 3
    • grid-template-columns: repeat(3, 1fr)
    • grid-columns: 1fr 3
  3. What is grid-template-areas used for?
    • Naming grid areas where children place themselves via grid-area
    • Defining the size of the grid's columns
    • Creating animations between cells