Easier BEM Modifiers with Sass
Sometimes you have very ugly Modifier Chains on a Element, like this:
<a href="#" class="button button--red button--big button--round button--secondary">Button</a>
Is not very sexy and harder to maintain. But what is when you can write this?
<a href="#" class="button--red--big--round--secondary">Button</a>
We don't need an @extend but we use a Base class, the additional 'class-names' would extend the Base Class.
// Setup the Root Element for the following chained Modifers
//
// @param {string} $name - The selector name
//
// @example
// @include chainroot('.text') {
// content: hello;
// }
@mixin chainroot($name) {
$r: str-slice($name,2,str-length($name));
@at-root {
#{$name}, [class^="#{$r}"] {
@content;
}
}
}
// Chain the Modifiers
//
// @param {string} $name - The selector name
// @param {string} $parent - Selector of the parent Element
//
// @example
// @include chain(bright, '.test') {
// color: #fff;
// }
@mixin chain($name,$parent) {
$par: str-slice($parent,2,str-length($parent));
@at-root {
[class^="#{$par}"][class*="--#{$name}"] {
@content;
}
}
}
Practical Example : http://sassmeister.com/gist/52b2dd9e0fe8a1ccab8d
Written by sascha fuchs
Related protips
2 Responses
If there are that many classes to define an element's style, we are doing OOCSS wrong.
The class should never describe the color itself. That usually means we are not abstracting a consistent piece of styling to be reused elsewhere. In this case, we have button--secondary
which usually does this theming so we can scrap button--red
.
Similarly, button--rounded
implies that not all buttons are rounded. This is inconsistent for the design and you should probably talk to your designer about standardizing on that. This means we would put the rounded properties into button
itself.
Now, we have simplified the classes and it seems reasonable (although not sure why a secondary action would require a big button).
<a href="#" class="button button--big button--secondary">Button</a>
tl;dr - Nice solution but we are inventing a problem for ourselves instead of solving real ones.
You may like csstyle, it gives a similar effect but leads to cleaner stylesheets and easy to add/remove individual modifiers.
http://csstyle.io