Search code examples
htmlcsscss-grid

How do I create a CSS grid layout like this?


I am trying to create a grid layout like this

enter image description here


I am able to create this layout. I am struggling with the first column, I don't want it to make the full height of the row. I want to achieve the grid layout like in the first image. Gray cells are just the divs where I would be adding move content later.

enter image description here

My CSS Code:

.cards_grid {
    grid-auto-columns: 1fr;
    grid-column-gap: 1.5rem;
    grid-row-gap: 1.5rem;
    -ms-grid-rows: auto 1.5rem auto;
    grid-template-areas:
        "first first first first second second second second second third third third"
        "fourth fourth fourth fourth fifth fifth fifth fifth sixth sixth sixth sixth";
    -ms-grid-columns: minmax(auto, 1fr);
    grid-template-columns: minmax(auto, 1fr);
}

I already tried the grid-layout-rows: masonry but it is not supported on most of the browsers.


Solution

  • Sticking with your method of explicitly defining grid areas you can use the same technique as you use on the horizontal placing - in that case you have defined 12 columns - on the vertical placing.

    It looks as though the grid is to have 5 rows, the first element extends down for 2 and the element below it (the 4th element) extends down for 3 and so on.

    This snippet removes bits of CSS which aren't needed, and sets the whole grid to have an aspect ratio 4:3. Obviously this may change in your particular requirement.

    .cards_grid {
      width: 100vmin;
      height: 75vmin;
      display: grid;
      grid-column-gap: 1.5rem;
      grid-row-gap: 1.5rem;
      grid-template-areas: "first  first  first  first  second second second second second third third third" "first  first  first  first  second second second second second third third third" "fourth fourth fourth fourth second second second second second third third third" "fourth fourth fourth fourth fifth  fifth  fifth  fifth  sixth  sixth sixth sixth" "fourth fourth fourth fourth fifth  fifth  fifth  fifth  sixth  sixth sixth sixth";
    }
    
    .cards_grid>div {
      background: gray;
    }
    
    .cards_grid>div:nth-child(1) {
      grid-area: first;
    }
    
    .cards_grid>div:nth-child(2) {
      grid-area: second;
    }
    
    .cards_grid>div:nth-child(3) {
      grid-area: third;
    }
    
    .cards_grid>div:nth-child(4) {
      grid-area: fourth;
    }
    
    .cards_grid>div:nth-child(5) {
      grid-area: fifth;
    }
    
    .cards_grid>div:nth-child(6) {
      grid-area: sixth;
    }
    <div class="cards_grid">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
    </div>