SCSS / Sass:如何将mixin更改为输出特定的CSS?

时间:2014-06-17 15:08:49

标签: css sass

我有一个用SCSS / Sass编写的函数,它使用map函数循环@each的每个项目。

  $classes-map: ("class-a": "doesntmatter",
          "class-b": "doesntmatter",
          'class-c': 'doesntmatter');

  @mixin function {
      @each $class, $property in $classes-map {
        %#{$class} {
          content: $property;
        }
        @for $i from 1 to 4 {
          &.#{$class}-#{$i} {
            @extend %#{$class};
          }
        }
      }
    }

在地图的每个项目上都有一个@for循环,用于制作包含komma的类列表,并且每次都有不同的数字。

这是输出应该是什么:

.class-a-1, .class-a-2, .class-a-3 {
  content: "doesntmatter";
}

.class-b-1, .class-b-2, .class-b-3 {
  content: "doesntmatter";
}

.class-c-1, .class-c-2, .class-c-3 {
  content: "doesntmatter";
}

我使用这段代码调用此函数:

.parent {
  &.child {
      @include function;
  }
}

CSS

.parent.child .parent.child.class-a-1, .parent.child .parent.child.class-a-2, .parent.child .parent.child.class-a-3 {
  content: "doesntmatter";
}
.parent.child .parent.child.class-b-1, .parent.child .parent.child.class-b-2, .parent.child .parent.child.class-b-3 {
  content: "doesntmatter";
}
.parent.child .parent.child.class-c-1, .parent.child .parent.child.class-c-2, .parent.child .parent.child.class-c-3 {
  content: "doesntmatter";
}

所需的CSS

.parent.child.class-a-1, .parent.child.class-a-2, .parent.child.class-a-3 {
   content: "doesntmatter";
}
.parent.child.class-b-1, .parent.child.class-b-2, .parent.child.class-b-3 {
   content: "doesntmatter";
}
.parent.child.class-c-1, .parent.child.class-c-2, .parent.child.class-c-3 {
   content: "doesntmatter";
}

如何更改@mixin function以解决此问题?

1 个答案:

答案 0 :(得分:3)

&

哦,这么近!由于您希望使用&链接/包含父选择器,因此mixin中的任何内容都应该效仿。丢失的部分是占位符&%#{$class}

<强> SCSS:

$classes-map: ("class-a": "doesntmatter",
        "class-b": "doesntmatter",
        'class-c': 'doesntmatter');

@mixin function {
  @each $class, $property in $classes-map {
    &%#{$class} {
      content: $property;
    }
    @for $i from 1 to 4 {
      &.#{$class}-#{$i} {
        @extend %#{$class};
      }
    }
  }
}

.parent {
  &.child {
    @include function;
  }
}

<强> CSS

.parent.child.class-a-1, .parent.child.class-a-2, .parent.child.class-a-3 {
  content: "doesntmatter";
}
.parent.child.class-b-1, .parent.child.class-b-2, .parent.child.class-b-3 {
  content: "doesntmatter";
}
.parent.child.class-c-1, .parent.child.class-c-2, .parent.child.class-c-3 {
  content: "doesntmatter";
}