0

I need help in creating a sass mixin.

I have a class called vertical3, which stacks the same same image above each other 3 times. I also get a property call overlap which can range from -2 to +1 for which I have defined classes below. these overlap classes sit on the same level as vertical 3.

As you can see they only adjust margin of the first two items. I would like to define a sass mixin for this.

<div class="vertical3 overlap-3">
    <img>
    <img>
    <img>
</div>


.vertical3 {
    flex-flow: column;
    flex-direction: column-reverse;
    justify-content: flex-start;
    align-items: center;
    img {
        max-height: 27%;
    }
}

.vertical3.overlap-2 {
    img:first-child {
        margin-top: -5%;
    }

    img:nth-child(2) {
        margin-top: -5%;
    }
}
.vertical3.overlap-1 {
    img:first-child {
        margin-top: -2.5%;
    }

    img:nth-child(2) {
        margin-top: -2.5%;
    }
}
.vertical3.overlap2 {
    img:first-child {
        margin-top: 5%;
    }

    img:nth-child(2) {
        margin-top: 5%;
    }
}
.vertical3.overlap1 {
    img:first-child {
        margin-top: 2.5%;
    }

    img:nth-child(2) {
        margin-top: 2.5%;
    }
}

I would like to accomplish something like this

.vertical3 {
    flex-flow: column;
    flex-direction: column-reverse;
    justify-content: flex-start;
    align-items: center;
    img {
        max-height: 27%;
    }
    @inlcude overlap(2.5%)
}

@mixin overlap($base){
    adding overlap-2 to overlap2 as classes
}
Han Che
  • 8,239
  • 19
  • 70
  • 116

1 Answers1

1

I've created the code below to show how you could achieve this.

You will call your mixin and pass in the larger of the margin values you want use, the mixin will then divide that value by 2 for the smaller margin, and output all the relevant classes you need.

@mixin overlap($base){
  &.overlap-2 {
    img {
      &:first-child, &:nth-child(2) {
        margin-top: -(($base) / 2);
      }
    }
  }
  &.overlap-1 {
   img {
      &:first-child, &:nth-child(2) {
        margin-top: -($base);
      }
    } 
  }
}

.vertical3 {
    flex-flow: column;
    flex-direction: column-reverse;
    justify-content: flex-start;
    align-items: center;
    background: red;
    width: 50px;
    height: 50px;
    img {
        max-height: 27%;
    }
    @include overlap(5%);
}
Sam Willis
  • 4,001
  • 7
  • 40
  • 59