Search code examples
htmlcssgrid-layoutcss-grid

Css-Grid: Trouble defining grid rules


Using CSS Grid, I'm trying to create a layout that looks like this:

enter image description here

How do I place the bottom (smaller) elements beyond the first row without using nested elements? The number of smaller elements can be anything. I tried using grid-auto-columns: 2fr; to accomplish my task, but it does not work.

Here's what I've tried so far: Codepen

main {
  display: grid;
  padding: 10px 0 10px 10px;
  grid-template: 1fr/repeat(6, 1fr);
  grid-template-areas: "a a a b b b";
  grid-auto-columns: 2fr;
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

main .a {
  grid-area: a;
}

main .b {
  grid-area: b;
}

.cat {
  height: 150px;
  background-size: cover;
  background-position: center;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 20px;
  background-color: green;
  color: #fff;
}

.cat:hover {
  background-color: #004800;
}
<main>
  <div class="cat a"></div>
  <div class="cat b"></div>
  <div class="cat c"></div>
  <div class="cat d"></div>
  <div class="cat e"></div>
  <div class="cat f"></div>
  <div class="cat g"></div>
  <div class="cat h"></div>
  <div class="cat i"></div>
</main>


Solution

  • The first thing I did is define how many columns the grid should be. Looking at your image, it made sense to me to go with 12 columns.

    enter image description here

    In the main element, I add the rule:

    grid-template-columns: repeat(12, 1fr);
    

    In your .cat rules, I added a few things. By default, each block takes up 4/12 columns.

    grid-column: span 4;
    

    The last part was dealing with the first two .cat blocks, a and b. No problem. They each take up 6/12 columns.

     &.a,
     &.b {
       grid-column: span 6;
     }
    

    And that's it. Here's a working demo.

    main {
      display: grid;
      padding: 10px 0 10px 10px;
      grid-template-columns: repeat(12, 1fr);
      grid-column-gap: 10px;
      grid-row-gap: 10px;
    }
    
    .cat {
      height: 150px;
      background-size: cover;
      background-position: center;
      overflow: hidden;
      position: relative;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      font-size: 20px;
      background-color: green;
      color: #fff;
      grid-column: span 4;
    }
    
    .cat:hover {
      background-color: #004800;
    }
    
    .cat.a,
    .cat.b {
      grid-column: span 6;
    }
    <main>
      <div class="cat a"></div>
      <div class="cat b"></div>
      <div class="cat c"></div>
      <div class="cat d"></div>
      <div class="cat e"></div>
      <div class="cat f"></div>
      <div class="cat g"></div>
      <div class="cat h"></div>
      <div class="cat i"></div>
    </main>