如何制作延伸父母的Sass mixin?

时间:2014-03-31 15:47:47

标签: css sass mixins

您可以在Sass中硬编码扩展选择器,如:

.box {
    width: 100px;
    height: 100px;
    color: red;
}

.box-green {
    @extend .box;
    color: green;
}

然后.box-green拥有.box的所有属性,以及其他附加属性。我想要做的是编写一个通用的mixin来做到这一点 - 获取一个类,将其所有属性添加到自己的类中,并为类名添加一个修饰符。如果像这样的伪代码有效(它没有),那将是理想的。

.box {
    width: 100px;
    height: 100px;
    color: red;

    @include make-modifier(&, green) {
        color: green;
    }
}

@mixin make-modifier(parent, modifier-name) {
   .#{$parent}-#{$modifier-name} {
        @content;
   }
}

有办法吗?即使只是最新版本也没关系。

1 个答案:

答案 0 :(得分:0)

我建议像这样一个更简单的解决方案

@mixin box($color:"") {
    width: 100px;
    height: 100px;
    color: red;

    @if $color !="" {
      &-#{$color} {
        color: $color;
      }
    }
}

.box {
  @include box(green);
}

输出将是:

.box {
  width: 100px;
  height: 100px;
  color: red;
}
.box-green {
  color: green;
}

示例:http://sassmeister.com/gist/04cb6a6fe14972c3ffe4

相关问题