← Learning Hub
Intermediate

CSS Grid

Grid lays things out in rows and columns at the same time. It is perfect for product galleries, photo walls and whole page layouts.

Grid is the most powerful layout tool in CSS. You define the columns (and optionally rows) on the parent, and the children fall into the cells automatically. With one line you can make a gallery that shows 1 column on a phone and 5 on a big screen, and with named areas you can draw a whole page layout - header, sidebar, main, footer - almost like a picture in your CSS.

Example
<!DOCTYPE html>
<html>
  <head>
    <style>
      .gallery {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
      }
      .gallery div { background: #e0f2fe; padding: 30px; text-align: center; border-radius: 8px; }
    </style>
  </head>
  <body>
    <div class="gallery">
      <div>1</div><div>2</div><div>3</div>
      <div>4</div><div>5</div><div>6</div>
    </div>
  </body>
</html>
▶ Try it yourself
  • grid-template-columns - how many columns and how wide.
  • 1fr - one share of the free space. 1fr 2fr makes the second column twice as wide.
  • repeat(3, 1fr) - three equal columns.
  • gap - space between rows and columns.

Responsive without media queries

This one line fits as many 160px-wide cards as there is room for, and stretches them to fill the row:

Example
.products {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 16px;
}
▶ Try it yourself

Page layout with grid areas

Example
<!DOCTYPE html>
<html>
  <head>
    <style>
      .page {
        display: grid;
        grid-template-columns: 200px 1fr;
        grid-template-areas:
          "header header"
          "side   main"
          "footer footer";
        gap: 8px;
        min-height: 300px;
      }
      header { grid-area: header; background: #fde68a; }
      aside  { grid-area: side;   background: #dcfce7; }
      main   { grid-area: main;   background: #e0e7ff; }
      footer { grid-area: footer; background: #fee2e2; }
      .page > * { padding: 10px; }
    </style>
  </head>
  <body>
    <div class="page">
      <header>Header</header>
      <aside>Menu</aside>
      <main>Main content</main>
      <footer>Footer</footer>
    </div>
  </body>
</html>
▶ Try it yourself
Flexbox or Grid? Use flexbox for one line of things (a menu, a row of buttons). Use grid when you need rows and columns together.
Key points
  • display: grid with grid-template-columns sets up the columns.
  • fr shares free space; repeat() avoids repetition.
  • repeat(auto-fit, minmax(...)) makes responsive grids without media queries.
  • Flexbox for one direction, grid for two.

📝 Test yourself

1. What does grid-template-columns: 1fr 1fr 1fr make?
2. Which property sets the space between grid items?
3. Fill in the display value that turns on grid layout:
display: ;