csssasscss-grid

Grid layout issue with alternating two-item rows


I am trying to figure out a grid layout which always has 2 posts in row. I would like the first item in row to take about 1/3 width and second to take 2/3 width, however in next row it should be vice versa.

Here is a layout example

1/3 2/3
2/3 1/3
1/3 2/3
2/3 1/3

This shouldn't be hardcoded in anyway and should work with any amount of children.

I did try something like this and some similar solutions

.latest-posts-block {
        display: grid;
        grid-template-columns: 1fr 2fr; 
    
        &__post:nth-child(4n + 1),
        &__post:nth-child(4n + 4) {
            grid-column: 1 / 2;
        }
    
        &__post:nth-child(4n + 2),
        &__post:nth-child(4n + 3) {
            grid-column: 2 / 3;
        }
    }

I can't quite figure out how to solve this, maybe anyone has worked on this issue before


Solution

  • A demo from my article that I recommend you read: https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers/#grid-patterns

    .grid {
      display: grid;
      grid-auto-rows: 100px;
      grid-auto-columns: 1fr;
      grid-gap: 5px;
    }
    .grid :nth-child(4n + 1){
      grid-column: span 2;
    }
    .grid :nth-child(4n + 4){
      grid-column: 2/span 2;
    }
    
    /**/
    .grid {
      max-width:600px;
      margin:auto;
      counter-reset:num;
    }
    .grid *{
      border:2px solid;
      font-size:30px;
      box-sizing:border-box;
      font-family:sans-serif;
      display:grid;
      place-content:center;
    }
    .grid *:before {
      content:counter(num);
      counter-increment:num;
    }
    <div class="grid">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>