csssassbem

Matching multiple BEM modifiers in Sass


I am using BEM, and have an element with multiple modifiers:

<div class="block__element block__element--m1 block__element--m2"></div>

I'm using SCSS and taking advantage of it to write nested rules compatible with BEM. If I want to write a rule where an element (like the above) has both the m1 and m2 modifier, is there a way to write that compatible with the way I'm currently writing them? This is the kind of syntax I'm after, but results in a syntax error:

.block {
    display: block;

    &__element {
        display: inline;

        &--m1 {
            background-color: red;
        }

        &--m2 {
            background-color: green;
        }

        // Syntax error
        &--m1&--m2 {
            background-color: yellow;
        }
    }
}

I can think of ways around this by using attribute selectors, but is there a neater way?

For the record, the compiled attribute selector should be:

.block__element--m1.block__element--m2

Solution

  • @3rdthemagical's answer did give me some inspiration for a better solution. Sass simply doesn't like & appearing after the beginning of the selector, but it doesn't mind it wrapped in #{}:

    .block {
        display: block;
    
        &__element {
            display: inline;
    
            &--m1 {
                background-color: red;
            }
    
            &--m2 {
                background-color: green;
            }
    
            // Correct!
            &--m1#{&}--m2 {
                background-color: yellow;
            }
        }
    }