Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing styles in SASS/SCSS without merging selectors

Tags:

css

extend

sass

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?

like image 855
Robert Koritnik Avatar asked Mar 08 '12 11:03

Robert Koritnik


2 Answers

Could you use a @mixin?

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

// Replace original
.notification {
  &.error {
    @include generic-error;
  }
}
like image 197
Andrew France Avatar answered Nov 22 '22 00:11

Andrew France


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

    .another-class {
      @extend %some-css;
    }
like image 32
Manjunath Hadimani Avatar answered Nov 22 '22 00:11

Manjunath Hadimani