有没有一种方法可以在包含mixin之后始终编写样式?

时间:2019-12-22 14:55:01

标签: sass scss-mixins

我正面临SCSS mixins的问题,因此必须重复相同的代码才能完成工作。我有以下SCSS代码:

@mixin column($count, $size) { // Can not make any change in this code.
  width: getWidth($count, $size);
  margin-left: 3%;
  margin-right: 3%;
}

@mixin desktop {
  @media screen and (min-width: 1024px) {
    @content;
  }
}

@mixin tablet {
  @media screen and (min-width: 768px) and (max-width: 1023px) {
    @content;
  }
}

@function getWidth($count, $size) {
  @return 50; // For example purpose only.
}

.c {
  @include desktop {
    @include column(10, large);
  }

  @include desktop {
    @include column(11, large);
  }

  margin: 0 auto;
}

被编译为:

.c {
  margin: 0 auto;
}

@media screen and (min-width: 1024px) {
  .c {
    width: 50;
    margin-left: 3%;
    margin-right: 3%;
  }
}

@media screen and (min-width: 1024px) {
  .c {
    width: 50;
    margin-left: 3%;
    margin-right: 3%;
  }
}

这里的问题是保证金被混合包覆盖。或者我必须重复相同的代码(重复代码),如下所示:

.c {
  @include desktop {
    @include column(10, large);
    margin: 0 auto; // Duplicate
  }

  @include desktop {
    @include column(11, large);
    margin: 0 auto; // Duplicate
  }

  margin: 0 auto;
}

获得:

.c {
    margin: 0 auto;
  }

  @media screen and (min-width: 1024px) {
    .c {
      width: 50;
      margin-left: 3%;
      margin-right: 3%;
      margin: 0 auto;
    }
  }

  @media screen and (min-width: 1024px) {
    .c {
      width: 50;
      margin-left: 3%;
      margin-right: 3%;
      margin: 0 auto;
    }
  }

还有什么更好的方法来删除重复的代码,这样我只需要编写一次代码?

1 个答案:

答案 0 :(得分:1)

尝试执行此操作以查看是否出现@media查询使您感到高兴。

.c {
  @include desktop {
    @include column(10, large);
  }
  @include desktop {
    @include column(11, large);
  }
  & {
    margin: 0 auto;
  }
}