We have many ways of selecting BEM elements with SCSS and LESS.
It is also all too easy to abuse BEM when using a CSS preprocessor.

To my knowledge, there are two types of frontenders:

The ones who nest their elements with &__element, like so:

   // Approach #1
 .very-long-component {
    display: block;

    &__child {
      background: red;
    }

    &__another-child {
      background: green;
    }

    &__third-child {
      background: blue;
    }
  }

And the ones who like everything neatly on the outermost level (guess which am I ;) ).

   // Approach #2
 .very-long-component {
    display: block;
  }

  .very-long-component__child {
    background: red;
  }

  .very-long-component__another-child {
    background: green;
  }

  .very-long-component__third-child {
    background: blue;
  }

I have found both approaches have their pros and cons. I tend to choose the 2nd approach the most, because I like collapsing everything and being able to get an overview of the whole file, but I do agree it can get a little redundant with long component names.

So, I came up with a compromise, where one does not need to nest (which is the part I hate the most about the first approach), but one can avoid having to write the component's name multiple times.

Avoiding nesting is also a good way to prohibit one from nesting block-element classes multiple times (like: .block__element__element).

Here's my approach:

In SCSS

  $c: '.very-long-component';

#{$c}{
  display: block;
}

#{$c}__child {
  background: red;
}

#{$c}__another-child {
  background: green;
}

#{$c}__third-child {
  background: blue;
}

In LESS

   @c: very-long-component;

.@{c} {
  display: block;
}

.@{c}__child {
  background: red;
}

.@{c}__another-child {
  background: green;
}

.@{c}__third-child {
  background: blue;
}

All three approaches will get compiled to the same CSS, so it is pretty much up to one's preferences.


1,319 4 33