CSS Grid

CSS Grid arranges content into rows and columns at the same time, making it ideal for full page and section layouts.

Where flexbox works in one direction, grid works in two. Set <code>display: grid</code>, describe your columns and optionally your rows, and items flow into the cells you define.

Defining Columns

Three equal columns

<!DOCTYPE html>
<html>
<head>
<style>
.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}
</style>
</head>
<body>

<div class="grid">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>

</body>
</html>

The fr Unit And repeat()

The <code>fr</code> unit represents a fraction of the leftover space, so three <code>1fr</code> tracks split the container evenly. The <code>repeat()</code> function saves you from typing the same track many times.

Four columns with repeat

<!DOCTYPE html>
<html>
<head>
<style>
.grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}
</style>
</head>
<body>

<div class="grid">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>

</body>
</html>
PropertyControls
grid-template-columnsThe number and size of columns
grid-template-rowsThe number and size of rows
gapSpace between rows and columns
grid-columnHow many columns an item spans
grid-rowHow many rows an item spans
Note: Use grid for the overall page or a section, and flexbox for a single row or column of items within it.

A Responsive Card Grid

auto-fit with minmax

<!DOCTYPE html>
<html>
<head>
<style>
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
}
</style>
</head>
<body>

<div class="cards">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
</div>

</body>
</html>

This single rule fits as many columns as will hold at least 220px, then lets them stretch to fill the row. The grid adds and removes columns on its own as the viewport changes, often without any media queries.

Exercise: CSS Grid

What's the difference between grid-template-columns and grid-template-areas?