CSS Tutorial · CSS Layout · Lesson 13 of 19

CSS Grid

Two-dimensional layouts with grid-template-columns, fr units, areas and auto-fit.

Grid containers

display: grid defines rows and columns:

Example 1Try it yourself
<style>
  .grid { display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 8px; font: 14px system-ui; }
  .grid div { background: #ede9fe; padding: 12px; border-radius: 6px; }
  .wide { grid-column: span 2; background: #c4b5fd !important; }
</style>
<div class="grid">
  <div>2fr</div><div>1fr</div><div>1fr</div>
  <div class="wide">spans 2 columns</div><div>1fr</div>
</div>
  • fr means "a fraction of the free space".
  • repeat(3, 1fr) is three equal columns.
  • gap spaces rows and columns.
  • Items can span tracks: grid-column: span 2.

Responsive without media queries

repeat(auto-fit, minmax(150px, 1fr)) fits as many columns as possible, each at least 150px wide — resize the window to watch it reflow:

Example 2Try it yourself
<style>
  .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; font: 14px system-ui; }
  .cards div { background: #ecfeff; border: 1px solid #67e8f9; border-radius: 8px; padding: 16px; }
</style>
<div class="cards">
  <div>Card 1</div><div>Card 2</div><div>Card 3</div><div>Card 4</div><div>Card 5</div>
</div>

Template areas

Name regions and place them visually:

Example 3Try it yourself
<style>
  .page {
    display: grid;
    grid-template-columns: 140px 1fr;
    grid-template-rows: auto 1fr auto;
    grid-template-areas:
      "header header"
      "nav    main"
      "footer footer";
    gap: 6px; height: 220px; font: 14px system-ui;
  }
  .page > * { padding: 8px; border-radius: 6px; }
  header { grid-area: header; background: #1e3a8a; color: white; }
  nav { grid-area: nav; background: #e2e8f0; }
  main { grid-area: main; background: #f8fafc; border: 1px solid #e2e8f0; }
  footer { grid-area: footer; background: #e2e8f0; }
</style>
<div class="page">
  <header>Header</header><nav>Nav</nav><main>Main</main><footer>Footer</footer>
</div>

Flexbox or grid? Flexbox for one direction (a row of buttons, a nav bar); grid for two-dimensional page and card layouts.

Test yourself

What does 1fr mean in a grid track?

  1. 1 pixel
  2. One fraction of the free space
  3. Full row
  4. First row
Show answer

Answer: One fraction of the free space