New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› CSS› CSS Grid Layout

CSS Grid Layout

💻 CSS

Build two-dimensional layouts with grid template columns, rows and gaps.

Lesson 6 of 9 Tutorial
0 of 9 completed

CSS Grid arranges items in rows and columns at the same time. It is ideal for page layouts, galleries and dashboards.

By the end of this lesson you can:
  • Create a grid container.
  • Define columns and rows.
  • Place items across tracks.

A Basic Grid

Set display: grid on the parent and define columns with grid-template-columns. The gap property spaces the items.

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.gallery img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

Fractional Units

1fr means one fraction of the available space. repeat(3, 1fr) creates three equal columns. Mixed tracks such as 240px 1fr give a fixed sidebar and a flexible main area.

Placing Items

Items can span several columns or rows. Use grid-column: span 2 for a wide card, or name lines and place items explicitly.

.featured {
  grid-column: span 2;
}

.layout {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
  gap: 24px;
}

Grid or Flexbox?

Use Grid when you need rows and columns together. Use Flexbox when items flow mainly in one direction, such as a navigation bar or a row of buttons.

Tip Use browser developer tools to inspect grid lines. The Grid overlay shows exactly where each track sits.

Practice

  1. Build a three-column photo gallery with a 16px gap.
  2. Make the first card span two columns.
  3. Create a page layout with a fixed sidebar and a flexible main area.

Hands-on exercise

Create a grid of six cards.
1. Use three equal columns on wide screens.
2. Add a 20px gap.
3. Make the first card span two columns.
4. Give each card a border and padding.

Recap

Grid controls rows and columns together. Use fractional units, gaps and spanning to build clean layouts.

Example

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.gallery img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

Exercises

Exercise 1. A responsive card grid Medium
Create a grid of six cards.
1. Use three equal columns on wide screens.
2. Add a 20px gap.
3. Make the first card span two columns.
4. Give each card a border and padding.
CSS exercise-1.css
Expected Output
Six cards in a three-column grid with the first card twice as wide.

Lesson Nav

Lesson sections