TutreNews Learn

Layout and responsive design

CSS Grid

Goal: Build two-dimensional layouts with columns, rows, fr units and gaps · 11 min

Grid lays items out in two dimensions at once, rows and columns. Use Flexbox for one axis and Grid for a whole layout.

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}
  • grid-template-columns defines the columns; grid-template-rows the rows.
  • The fr unit means "one fraction of the free space": 1fr 2fr gives the second column twice the width of the first.
  • repeat(3, 1fr) is shorthand for 1fr 1fr 1fr.
  • gap (or row-gap / column-gap) sets the gutters between cells.
  • Mixing is fine: 200px 1fr is a fixed sidebar and a flexible main area.
  • Placing items: grid-column: 1 / 3 lets an item span from grid line 1 to line 3 (two columns); grid-column: span 2 does the same.
  • Responsive without media queries: grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)) creates as many 200px+ columns as fit.

Calculation: a 330px wide grid with repeat(2, 1fr) and gap: 30px has (330 − 30) / 2 = 150px per column. The gap is subtracted first, then the fractions are divided.

Worked example: A page layout with sidebar

  1. Two columns: a fixed 220px sidebar and a flexible main area.
  2. grid-template-columns: 220px 1fr;
  3. The header can span both columns with grid-column: 1 / -1.
.page {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 1rem;
}
header { grid-column: 1 / -1; }