Skip to content

Instantly share code, notes, and snippets.

@rubyconvict
Forked from mmintel/gist:045ffce76b00b327bfc0
Last active October 19, 2015 12:45
Show Gist options
  • Save rubyconvict/bd79ef1943a6b32957a3 to your computer and use it in GitHub Desktop.
Save rubyconvict/bd79ef1943a6b32957a3 to your computer and use it in GitHub Desktop.
/**
* BEM Mixin for Sass (v3.4.0)
*
* Block / Element / Modifier
*
* Example:
*
* @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;
* }
* }
* }
*
*
* Result:
*
* .test {
* background: red;
* }
* .test__element {
* font-size: 14px;
* }
* .test__element--big {
* font-size: 18px;
* }
* .test--modifier {
* color: blue;
* }
* .test--modifier .test__subelement {
* background: gray;
* }
*
*/
$elementSeparator: '__' !default;
$modifierSeparator: '--' !default;
@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;
@if $modifierStart {
@return str-slice($selector, 0, $modifierStart);
}
@else {
@return $selector;
}
}
@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;
}
}
}
@rubyconvict
Copy link
Author

TODO: verify libsass compatibility: sass/libsass#1250

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