SCSS:将多个类传递给mixin

时间:2013-05-09 20:47:28

标签: css sass

我经常使用mixins来存储代码块。例如:

   @mixin ui-spot-badges($ui-spot-badges: ui-spot-badges) {

    .#{$ui-spot-badges} {   
  position:relative; 
    @content;

    &:after {
    content:""; 
position:absolute;
background:red;
    }
    }

    }

    @include ui-spot-badges(myclass); 

如何将多个类传入mixin。例如。

  @include ui-spot-badges(myclass, myclass2); 

获取

.myclass, myclass2 {
  position:relative; 
}

.myclass:after, .myclass2:after {
    content:""; 
position:absolute;
background:red;
}

1 个答案:

答案 0 :(得分:5)

最有效的方法是将您的选择器列表作为字符串传递:

@include ui-spot-badges('.myclass, .myclass2');

否则,您必须进行一些循环才能正确生成选择器。

@mixin ui-spot-badges($badges...) {
    $selectors: ();
    @each $b in $badges {
        $selectors: append($selectors, unquote('.#{$b}'), comma);
    }

    #{$selectors} {
        position:relative; 
        @content;

        &:after {
            content:""; 
            position:absolute;
            background:red;
        }
    }
}

@include ui-spot-badges(a, b);

输出:

.a, .b {
  position: relative;
}
.a:after, .b:after {
  content: "";
  position: absolute;
  background: red;
}