CSS Grid

CSS Grid places elements in rows and columns at the same time. You switch it on for the parent element with display: grid and describe the columns in one property.

Syntax

.container {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;
  gap: 16px;
}
.item { grid-column: 1 / 3; }

Key properties and functions

ItemWhat it does
display: gridmakes the element a grid container; its direct children become grid items
grid-template-columnsthe grid's columns: how many and how wide
grid-template-rowsrow heights (by default, sized to content)
fra "share of free space" unit: 1fr 2fr splits it 1 : 2
repeat()repetition: repeat(3, 1fr) gives three equal columns
minmax()size limits for a column: minmax(140px, 1fr) is never narrower than 140px
auto-fill / auto-fitas many columns as fit; auto-fit also stretches them into empty space
gapgaps between rows and columns
grid-column / grid-rowhow many columns or rows an item spans: span 2 or 1 / 3

Example

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 12px;
}
.grid div {
  padding: 12px;
  background: #e0f2fe;
  border: 1px solid #0284c7;
}
.wide {
  grid-column: span 2;
}
<div class="grid">
  <div class="wide">1 (span 2)</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

Result

▶ Open in HTML Editor

Good to know

  • repeat(auto-fill, minmax(140px, 1fr)) is a responsive grid without a single media query: there are fewer columns as the window gets narrower.
  • Grid is for two-dimensional layouts (a page grid, a gallery); flexbox is for one direction (a menu, a row of buttons). They are often combined.
  • Items are placed into cells automatically; grid-column and grid-row are only needed when an item has to take a specific place or several cells.

Sources and specification

See also