Reusing styles in SASS/SCSS without merging selectors

Robert Koritnik picture Robert Koritnik · Mar 8, 2012 · Viewed 10k times · Source

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

#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).

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? 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.

#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?

Answer

Andrew France picture Andrew France · Mar 8, 2012

Could you use a @mixin?

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

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