โ† Home

Create a Card Layout with CSS Grid

You can create a card layout with just a few lines of CSS Grid code!

View on Egghead

First, we need a parent HTML element with some child elements inside it. For example, this main element with six card divs within it.

<main class="card-container">
  <div class="card">
    <p>hi</p>
  </div>
  <div class="card">
    <p>hi</p>
  </div>
  <div class="card">
    <p>hi</p>
  </div>
  <div class="card">
    <p>hi</p>
  </div>
  <div class="card">
    <p>hi</p>
  </div>
  <div class="card">
    <p>hi</p>
  </div>
</main>

We will add some CSS to our cards to make them stand out on the white background:

.card {
  background-color: #006b80;
  color: white;
  width: 100%;
}

Then, we'll make the .card-container element into a grid container by adding display: grid; to it.

Then, we will use the fr fractional units that CSS Grid introduces. If we do grid-template-columns: 1fr 2fr 1fr;, then the first card will take up 1/4 of the page, the second 2/4, and the third 1/4 since 1 + 2 + 1 = 4.

In the end product, we want cards that take up 1/3 of the page. So, we would use grid-template-columns: 1fr 1fr 1fr; instead. We could also write this as grid-template-columns: repeat(3, 1fr); to say that we have 1fr repeated 3 times.

We can also have a grid-gap to add a gutter between each card.

.card-container {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
}

๐ŸŽ‰ Now we have a card layout!

Be the first to know about my posts!

Share this post with a friend!

LinkedIn
Reddit