Mixins in SASS are great, however, there is a downside to using them for your OOSASS. Mixins bloat the output code. Every time you call a mixin it includes the output of the mixin in your final CSS. The obvious solution is placeholders, but placeholders don’t work well with parameters or with BEM-style css class names.
I’ve come up with a solution that solves both problems. I lets you use a mixin for your OOSASS class, it lets you inherit from this OOSASS class and also produces efficient output using placeholders.
Say we are styling the following markup:
We might start by making a mixin for this component;
1
2
3
4
5
6
7
8
@mixin article {
&__title {
font-size: 18px;
}
&__body {
font-size: 12px;
}
}
And then use it:
The problem here comes when we try to apply this mixin to another component.
This is going to output this, which duplicates our CSS:
What we want to do here is to create placeholders for every element in our mixin “class”, and use them with extend inside our mixin.
Now our previous code which did the @include article on the two components generates this:
Now I have a reusable mixin that produces optimized SASS! But what if I want to override some style of an instance of a component? This is fine. Since we included @content in our mixin ‘class’ you can do this:
So what we have here is in essence OOSASS. .another-article is an instance of article. And it add styling to the title to color it black. But what if we want to make a subclass of article? Say we want it to be a featured article and have larger bolder headlines? We can do this:
featured-article inherits from article. It overrides font-size and adds font-weight. Here’s an example of using two articles and two featured articles
And the CSS output it produces:
Because of the single level of specificity of BEM, the overrides work perfectly the and later rules for font-size win for featured articles. It would be nice to properly override the font-size and get it to exclude the first font-size declaration automatically, but sass doesn’t really provide a mechanism to do this sort of thing. Here’s a live example of the above on sassmeister if you want to play with it.