Search code examples
cssgrid

How do I make this grid in my vue and scss project?


Does anyone have any ideas how I could make such a grid?

This is my vue part:

<div class="projects">
  <Project v-for="project in projects" :key="project.title" :title="project.title" :img="project.img" :link="project.link" />
</div>

And for the project this css:

.project {
    overflow: hidden;
}

.img {
    width: 100%;
}
img {
    flex-grow: 1;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}    

The grid I want to make

I could also add JS if that is what it needs. It's in vue so yeah.

I tried the following code:

.projects {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 0.5rem;
  width: min(100%, 2000px);
  margin: 0 auto;
  padding: 0 1rem;
}

.project:nth-child(2n+1) {
  margin-top: 1rem;
}

But now at the right column, the picture below does not neatly match the picture above. Because of the row...


Solution

  • You simply use a 2-column grid and offset all elements in the 2nd column. You can address all elements within the second column by using nth-child(even). Then you add a negative margin-top and a positive margin-bottom with the same value which will offset the elements as you need:

    section {
      display: grid; 
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 1em;
      padding-top: 10vh;
    }
    
    section > div:nth-child(even) {
      margin: -10vh 0 10vh 0;
    }
    
    
    
    /* for visualization purpose only */
    div {
      min-height: 30vh;
      border: 2px dashed red;
    }
    <section>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </section>

    SASS/LESS could simplify it to:

    section {
      display: grid; 
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 1em;
      padding-top: 10vh;
      > div {
        &:nth-child(even) {
          margin: -10vh 0 10vh 0;
        }
      }
    }