Skip to content

Instantly share code, notes, and snippets.

@mmintel
Last active October 12, 2020 10:34
Show Gist options
  • Save mmintel/045ffce76b00b327bfc0 to your computer and use it in GitHub Desktop.
Save mmintel/045ffce76b00b327bfc0 to your computer and use it in GitHub Desktop.
BEM mixins in Sass 3.4
$elementSeparator: '__';
$modifierSeparator: '--';
@function containsModifier($selector) {
$selector: selectorToString($selector);
@if str-index($selector, $modifierSeparator) {
@return true;
} @else {
@return false;
}
}
@function selectorToString($selector) {
$selector: inspect($selector); //cast to string
$selector: str-slice($selector, 2, -2); //remove brackets
@return $selector;
}
@function getBlock($selector) {
$selector: selectorToString($selector);
$modifierStart: str-index($selector, $modifierSeparator) - 1;
@return str-slice($selector, 0, $modifierStart);
}
@mixin b($block) {
.#{$block} {
@content;
}
}
@mixin e($element) {
$selector: &;
@if containsModifier($selector) {
$block: getBlock($selector);
@at-root {
#{$selector} {
#{$block+$elementSeparator+$element} {
@content;
}
}
}
} @else {
@at-root {
#{$selector+$elementSeparator+$element} {
@content;
}
}
}
}
@mixin m($modifier) {
@at-root {
#{&}#{$modifierSeparator+$modifier} {
@content;
}
}
}
@include b(test) {
background: red;
@include e(element){
font-size: 14px;
@include m(big) {
font-size: 18px;
}
};
@include m(modifier) {
color: blue;
@include e(subelement) {
background: gray;
}
}
}
@johngerome
Copy link

Hi Mintel,
I tried it on sassmeister and i got an error
in line 21 it's Invalid null operation: "null minus 1"

$modifierStart: str-index($selector, $modifierSeparator) - 1;

str-index($selector, $modifierSeparator) is null

@mmintel
Copy link
Author

mmintel commented Aug 24, 2014

Hi @johngerome,

thanks for your comment! That happens if you don't run a last test... it failed because I moved the call of getBlock() out of @if containsModifier($selector).

It's working now and I also prepared a Sassmeister gist: http://sassmeister.com/gist/6dac17c87fcf2d1555c4

@ashishm1991
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment