在SASS/SCSS中重复使用样式而不合并选择器

19
如果我在SCSS中有这样一个样式定义:

If I have a style definition in SCSS that looks like this:

#someid {
    ...
    .message {
        ...
        &.error {
            // overrides of .message class
        }
    }
}

我在UI中显示了一些消息,可以是普通消息(具有 .message 类),也可以是错误消息(同时具有 .message.error 类)。

现在我有一个显示类似信息的不同元素,既有正常的也有错误的,这就是为什么我想复制错误设置的原因。

如何在不将样式放在单独的类中并扩展/使用它在两个 .error 样式中或使用 mixin 实现相同目的的情况下使用 @extend 指令?我只想重用相同的样式定义。

问题在于当我使用 @extend 时,它会结合所有种类的类继承。

#otherid {
    ...
    .notification {
        ...
        &.error {
            // should use the other ".error" style
        }
    }
}

问题在于编译后的结果具有这种样式定义,其中混合了合并选择器:

#someid .message.error,
#someid #otherid .message.notification.error,
#otherid #someid .message.notification.error

虽然我更愿意只有这两个:

#someid .message.error,
#otherid .notification.error

这能做到吗?

2个回答

29

你能否使用@mixin?

// Define here
@mixin generic-error {
  // Error styling
}

// Replace original
.notification {
  &.error {
    @include generic-error;
  }
}

这与在两个其他类中分别扩展一个单独的类相同/类似...但这也是可能的解决方案之一。没错。 - Robert Koritnik
似乎这是最好的(最差的)解决方案,因为混合(mixins)并没有真正渲染到生成的CSS中。 - Robert Koritnik

2
    %some-css {
      //CSS goes here.
    }

    .another-class {
      @extend %some-css;
    }

6
请勿仅仅发布代码作为答案,同时还需提供解释说明代码的功能以及它如何解决问题。带有解释的答案通常更有帮助、质量更高,并且更容易吸引点赞。 - Ran Marciano

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接