SASS Mixins For Easier BEM Coding

Hey there!

If you’ve tried using BEM (Block Element Modifier) methodology to make your SCSS more manageable, I’ve got a handy set of mixins you can use. I’ve had some pretty good success with them so far.

First let me share the mixins:

$element-prefix:  '__';
$modifier-prefix: '--';

@mixin block($block-name) {
  @at-root {
    .#{$block-name} {
      @content;
    }
  }
}

@mixin element($element-name) {
  $super-name: str-slice(nth(nth(&, 1), 1), 2);
  @at-root {
    .#{$super-name}#{$element-prefix}#{$element-name} {
      @content;
    }
  }
}

@mixin modifier($modifier-name) {
  $super-name: str-slice(nth(nth(&, 1), 1), 2);
  @at-root {
    .#{$super-name}#{$modifier-prefix}#{$modifier-name} {
      @extend .#{$super-name};
      @content;
    }
  }
}

Go ahead and copy that into your project. You can also access this code from a public gist, here.

So, what’s happening here? The intention with these mixins is to reduce some of the verbosity when writing BEM style SCSS (and markup). Here’s an example of how you’d use these mixins. Here’s some pseudo-SCSS:

@include block(card) {
  //...

  @include modifier(editable) {
    //...
  }

  @include element(content) {
    //...

    @include modifier(field) {
      //...
    }
  }
}

Notice that with these mixins, you can now define the modifiers and elements of a given block, by nesting them within the block’s definition.

And yes, I said that right, even a block can have a modifier. In my opinion, this makes sense. A card could be of a couple different types: say a regular card (without a modifier) or an editable card, which can have some custom styles of it’s own.

That means that you can have a class like .card--editable__content. Which might seem like we’re breaking some rules here, since there’s a modifier coming before an element. What we’re saying here, though, is that this is a class which points to the content elements of editable cards. That can often be useful.

You might have also noticed that you have the flexibility to define different BEM delimiters at the top. Though, I’m sticking with the conventional -- and __ here.

A last thing that these mixins do for you, is reduce the verbosity in your markup. If you specify a class of .card--editable on one of your elements, for example, these mixins are smart enough to include the .card styles as well. So html like the following:



<div class="card card--editable"></div>


Can now be written just as:



<div class="card--editable"></div>


So much better!

This last point was actually my motivation for creating these mixins in the first place. It always bothered me having to repeat myself over and over again. .card--editable should imply .card, right?

Well, I hope this helps some folks out there. Feel free to reach out if you have any questions.

Cheers!