Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching multiple BEM modifiers in Sass

Tags:

css

sass

bem

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
like image 624
Robert Avatar asked Dec 05 '17 11:12

Robert


People also ask

Can you use BEM with sass?

BEM and SASS combination The & essentially saves us rewriting the parent selector over and over. What we end up with is the styles for our nav component encapsulated into a single block. Having the classes in one block like this makes it easy to identify, edit and move around.

Should you use Bem CSS?

Benefits of using BEM Because of its unique naming scheme, we won't run into conflicts with other CSS names. BEM also provides a relationship between CSS and HTML. Ambiguous names are hard to maintain in the future⁣. Overall, BEM is my favourite CSS naming scheme, and I strongly suggest you try using it too!

What is Bem methodology?

BEM is a front-end naming method for organizing and naming CSS classes. The Block, Element, Modifier methodology is a popular naming convention for class names in HTML and CSS.

How do you write bem?

BEM names intentionally use double underscores and double hyphens instead of single to separate Block-Element-Modifier. The reason is so that single hyphens can be used as word separators. Class names should be very readable, so abbreviation isn't always desirable unless the abbreviations are universally recognizable.


1 Answers

@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;
        }
    }
}
like image 156
Robert Avatar answered Dec 06 '22 05:12

Robert