如何将标签作为scss mixin参数传递?

时间:2018-11-19 05:36:17

标签: css sass scss-mixins

我正在创建一个针对子元素的mixin。 例。 定位具有父级<a>的父级的所有section---blue标签

我认为可以将标记作为参数传递,如下所示 但是我没有得到想要的结果

SCSS

@mixin themeParent ($child) {
    &--blue $child {
        color: getColour("theme", "bluehighlight");
    }

    &--green $child {
        color: getColour("theme", "greenhighlight");
    }

    &--purple $child {
        color: getColour("theme", "purplehighlight");
    }
}

.section {
 @include themeParent(a);
}

我本以为会编译为

.section--blue a {
color: blue;

}

有人可以向我解释为什么吗?

3 个答案:

答案 0 :(得分:2)

$child放入#{$child}

@mixin themeParent ($child) {
    #{$child} {
        color: #000;
    }
}

.section {
    @include themeParent(a)
}

输出:

.section a {
  color: #000;
}

答案 1 :(得分:1)

@mixin themeParent ($child) {
    &--blue #{$child} {
        color: blue;
    }
}

输出:.section--blue a { color: blue; }


如果您想获得更多的特异性,只需添加另一个&

@mixin themeParent ($child) {
    &#{&}--blue #{$child} {
        color: blue;
    }
}

输出:.section.section--blue a { color: blue; }


如果您想提高可伸缩性,只需遍历所需的颜色即可:

@mixin themeParent ($child) {
  $colors: red, blue, green;
  @each $color in $colors {
    &#{&}--#{$color} #{$child} {
        color: $color;
    }
  }
}

答案 2 :(得分:0)

如果我简单地说明这一点,则无需将标记作为参数传递给mixin函数,您应该传递元素的颜色。

<div className="section--blue">
                    <a>section blue</a>
</div>

<div className="section-green">
           <a>section green</a>        
</div>

mixin和CSS

@mixin themeParent ($color) {
   color:$color;
 }
.section{
    &--blue {
        a{
            @include themeParent(blue);
        }
    }
    --green{
        a{
            @include themeParent(green);
        }
    }
}

希望这很有用。

相关问题