如何使用Sass Mixin追加一组类

时间:2018-07-09 15:22:39

标签: sass scss-mixins

在创建Sass Mixin时需要帮助。

我有一个叫做Vertical3的类,该类将相同的图像彼此叠放3次。我还得到了一个属性调用重叠,其范围从-2到+1,下面将为其定义类。这些重叠的类与纵向3位于同一级别。

如您所见,它们仅调整前两个项目的边距。我想为此定义一个混蛋。

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

1 个答案:

答案 0 :(得分:1)

我已经创建了下面的代码来展示如何实现此目标。

您将调用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%);
}