Write CSS to create a responsive card grid using CSS Grid

Description: Create a grid of four cards that fits as many columns as the screen allows, and stacks on a phone.

Hint:

  • Use display: grid with grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)).

CSS responsive card grid

<style>
  .cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
  }
  .card {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 14px;
  }
</style>

<div class="cards">
  <div class="card">Card 1</div>
  <div class="card">Card 2</div>
  <div class="card">Card 3</div>
  <div class="card">Card 4</div>
</div>

Output in the browser:

Output in the browser
Card 1
Card 2
Card 3
Card 4

How it works

  • minmax(150px, 1fr) says each column is at least 150px wide, and can grow to share the free space.
  • auto-fit makes as many columns as fit. On a narrow phone the cards come in one column.

Read CSS Grid.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.