将循环中的sass变量作为没有值的选择器传递

时间:2017-06-14 21:30:39

标签: sass gulp-sass

除了已经建立的选择器之外,我想使用mixin为我提供根据需要传递其他选择器作为参数的选项。但我在这里得到一个错误。不知道我错过了什么,除非你不能在循环中使用变量而不将值传递给每个项目,而且我认为这一切都是错误的。

@mixin light-section-text( $selectors: null ) {

  @if ( $selectors ) {
    @for $i from 1 through length( $selectors ) {
      #{nth( $selectors, $i )},
    }
  }
  p,
  address,
  li {
    color: $white;
  }
}

在这种情况下,@include light-section-text( "body", "strong", "strong a" );的所需输出为:

body,
strong,
strong a,
p,
address,
li {
  color: #fff; }

1 个答案:

答案 0 :(得分:0)

First, you can't directly pass the selectors list to the mixin function as it would cause $selectors to be the first string. So you have to first declare a list variable and then pass that variable to the function.

Second, you should simply use the Placeholders functionality offered by Sass which makes use of @extend and the % character.

%color{
  color: white;
}
@mixin light-section-text( $selectors: null ) {

  @if ( $selectors ) {
      @for $i from 1 through length( $selectors ) {
        #{nth( $selectors, $i )}{
          @extend %color;
        }
      }
  }
  p,
  address,
  li {
     @extend %color;
  }
}
$list-variable: "body", "strong", "strong a";

@include light-section-text($list-variable);

Alternate Method

You don't even need to use the mixin function as this task can be handled by sass placeholder alone.

$white : white;

%color{
  color: $white;
}
$list-variable: "body", "strong", "strong a", "p", "address", "li";

@each $item in $list-variable {
    #{$item} {
      @extend %color;
    }
}