So, my good buddy Wes has fallen in love with BEM, that glorious HTML/CSS methodology that adds reinforced steel to your front-end framework. And he discovered the other day that someone has written a SASS mixin for writing BEM. But…but…I’m more of a Stylus fanboy. Where’s my mixin? Oh, here it is…
But first, a downside
Wes and I discussed the value of actually using a BEM mixin. After all, it could make BEM appear less legible. Not only that, BEMifiying isn’t that hard in Stylus today. If you’re using Stylus, and you’re writing BEM for a header, it could look like this:
.header display: flex flex-direction: column &__nav display: flex flex-direction: row &--vertical flex-direction: column
We’re relying on the &
keyword in Stylus, which means, “get the parent selector, and put it here”. So in writing &__
we’re saying, “get the parent selector, and now add a double-underscore.”
Hold shift, press 7; hold shift, press - twice. Three keystrokes while holding shift, and that gets you the following CSS:
.header { display: flex; flex-direction: column; } .header__nav { display: flex; flex-direction: row; } .header--vertical { flex-direction: column; }
So why use a mixin at all?
If something’s already simple, why overcomplicate it?
- It’s another layer of abstraction that keeps you DRY
- If you need to modify your BEM approach; switch from
__
to_
, you can do that
If you’re in the habit of commenting out your HTML, you’ll find validation errors in using the --
for modifiers. Using a mixin allows you to easily fix that in one place, rather than many.
The mixin
Here you go. The Stylus version is a bit cleaner than the SASS version, but the impact to the user is identical: +m(name)
for modifiers, and +e(name)
for elements.
And, yes, +m()
is four keystrokes instead of three — and it requires you to take a finger off of shift — but is it oh so terrible that you’ve now centralized your naming methodology?