简体   繁体   English

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

[英]Reusing styles in SASS/SCSS without merging selectors

If I have a style definition in SCSS that looks like this:如果我在 SCSS 中有一个如下所示的样式定义:

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

So I display some kind of messages in my UI which can be normal message (have .message class) or errors (have both .message.error classes).所以我在我的 UI 中显示某种消息,它们可以是普通消息(具有.message类)或错误(具有.message.error类)。

Now I have a different element that displays similar info in normal an erroneous way, that's why I would like to replicate error settings.现在我有一个不同的元素,它以正常和错误的方式显示类似的信息,这就是我想复制错误设置的原因。

How do I use @extend directive without putting styles in a separate class and then extending/using it in both .error styles or using a mixin for the same purpose?如何使用 @extend 指令而不将样式放在单独的类中,然后在.error样式中扩展/使用它,或者出于相同目的使用 mixin? I would just like to reuse the same style definition.我只想重用相同的样式定义。

The problem is that it combines all kinds of class inheritance when I do an @extend .问题在于,当我执行@extend时,它结合了各种类继承。

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

The problem is that the compiled results has this style definition which is a mix and match of merged selectors:问题是编译结果具有这种样式定义,它是合并选择器的混合和匹配:

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

While I would rather have just these two:虽然我宁愿只有这两个:

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

Can this at all be done?这完全可以做到吗?

Could you use a @mixin?你能用@mixin吗?

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

// Replace original
.notification {
  &.error {
    @include generic-error;
  }
}
    %some-css {
      //CSS goes here.
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM