如何使用 sass mixin 附加一组 类

how to use sass mixin to append a set of classes

我需要帮助创建 sass mixin。

我有一个名为 vertical3 的 class,它将同一张图片堆叠 3 次。我还得到一个 属性 调用重叠,范围从 -2 到 +1,我在下面定义了 classes。这些重叠 classes 位于与垂直 3.

相同的水平

如您所见,他们只调整了前两项的边距。我想为此定义一个 sass mixin。

<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%;
    }
}

我想完成这样的事情

.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
}

我创建了下面的代码来展示如何实现这一点。

您将调用您的 mixin 并传入您要使用的较大边距值,然后 mixin 将该值除以 2 以获得较小的边距,并输出您需要的所有相关 类。

@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%);
}