Skip to content

Instantly share code, notes, and snippets.

@chapterjason
Last active May 4, 2016 11:49
Show Gist options
  • Save chapterjason/751359989e3567c82f04d21a10be3b90 to your computer and use it in GitHub Desktop.
Save chapterjason/751359989e3567c82f04d21a10be3b90 to your computer and use it in GitHub Desktop.
BEM Mixin
/**
* ==============================
* Configuration
* ==============================
**/
$elementSeparator: '__';
$modifierSeparator: '--';
$statePrefix: '.is-';
/**
* ==============================
* Base Functions
* ==============================
**/
@function selectorToString($selector) {
$selector: inspect($selector);
$selector: str-slice($selector, 2, -2);
@return $selector;
}
@function contains($selector, $string){
$selector: selectorToString($selector);
@if str-index($selector, $string) {
@return true;
} @else {
@return false;
}
}
@function getBlock($selector, $string) {
$selector: selectorToString($selector);
$stringStart: str-index($selector, $string) - 1;
@return str-slice($selector, 0, $stringStart);
}
/**
* ==============================
* Alias Functions
* ==============================
**/
@function containsModifier($selector) {
@return contains($selector, $modifierSeparator);
}
@function containsState($selector) {
@return contains($selector, $statePrefix);
}
@function containsElement($selector) {
@return contains($selector, $elementSeparator);
}
@function getModifierBlock($selector) {
@return getBlock($selector, $modifierSeparator);
}
@function getStateBlock($selector) {
@return getBlock($selector, $statePrefix);
}
@function getElementBlock($selector) {
@return getBlock($selector, $elementSeparator);
}
/**
* ==============================
* BEM Mixins
* ==============================
**/
@mixin block($block) {
.#{$block} {
@content;
}
}
@mixin element($element) {
$selector: &;
@if containsModifier($selector) {
$block: getModifierBlock($selector);
@if containsElement($block){
$block: '.'+getElementBlock($block);
}
@at-root {
#{$selector} {
#{$block+$elementSeparator+$element} {
@content;
}
}
}
} @else if containsState($selector) {
$block: getStateBlock($selector);
@if containsElement($block){
$block: '.'+getElementBlock($block);
}
@at-root {
#{$selector} {
#{$block+$elementSeparator+$element} {
@content;
}
}
}
} @else {
@at-root {
#{$selector+$elementSeparator+$element} {
@content;
}
}
}
}
@mixin modifier($modifier) {
@at-root {
#{&}#{$modifierSeparator+$modifier} {
@content;
}
}
}
@mixin state($state) {
@at-root {
#{&}#{$statePrefix+$state} {
@content;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment