Reusing styles in SASS/SCSS without merging selectors

12,896

Solution 1

Could you use a @mixin?

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

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

Solution 2

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

    .another-class {
      @extend %some-css;
    }
Share:
12,896
Robert Koritnik
Author by

Robert Koritnik

Remote web developer, consultant, enthusiast, geek.

Updated on June 23, 2022

Comments

  • Robert Koritnik
    Robert Koritnik almost 2 years

    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?

  • Robert Koritnik
    Robert Koritnik about 12 years
    Well that's the same/similar to having a separate class and extend it in both of the other classes... but it's also one of the possible solutions. That's true.
  • Robert Koritnik
    Robert Koritnik about 12 years
    .. sesms to be the best (of the worst) solution because mixins don't really get rendered into resulting CSS.
  • Ran Marciano
    Ran Marciano over 3 years
    Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes