HTML and CSS · Lesson 9 of 12

CSS Grid

Grid lays things out in two directions at once: rows and columns. Use it for page layouts and card galleries; use flexbox for a single row or column.

Columns, fr and gap

display: grid; grid-template-columns: 200px 1fr; makes two columns: a fixed 200px sidebar and the rest. fr is a share of the free space: 1fr 2fr splits it one third to two thirds. repeat(3, 1fr) means three equal columns, and gap spaces them.

Try itEdit the code: the page updates as you type

Responsive cards without media queries

grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)) fits as many columns as there's room for, each at least 160px wide, and stretches them to fill the row. Shrink the preview's width (or look on a phone) and the cards rearrange by themselves.

Try itEdit the code: the page updates as you type

Your turn

Make a photo gallery: 3 columns on wide screens that drop to fewer on narrow ones automatically, with the first photo spanning 2 columns.

ExerciseEdit the code: the page updates as you type
Show a solution
<style>
  .gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; }
  .gallery div { background: #d0ebff; height: 80px; border-radius: 8px; }
  .gallery .big { grid-column: span 2; }
</style>
<div class="gallery">
  <div class="big"></div><div></div><div></div><div></div><div></div>
</div>

In the interview

Flexbox or grid?

Flexbox for one dimension (a row of buttons, a navbar, items in a line); grid for two (a page layout, a gallery). They work well together: a grid of cards whose insides use flexbox.

What does the fr unit mean?

A fraction of the free space in the grid container after fixed sizes and gaps: 1fr 1fr gives two equal columns; 1fr 3fr gives a quarter and three quarters.

auto-fit vs auto-fill?

Both make as many columns as fit. With auto-fit, empty columns collapse so the items stretch to fill the row; with auto-fill, the empty columns stay, keeping items at their minimum size.

Your progress stays on this device.