I’m working on a project with a team of developers who are trying out the BEM syntax for their class names. I’ve tried BEM before, but I’m not a huge fan of underscores (for no particularly good reason) so I tend to use a modified version that avoids those characters. Still, when it comes to coding style—tabs vs. spaces, camelCasing, underscores, hyphens, or whatever—my personal opinion takes a back seat to the group consensus. And on this project, the group has opted for proper BEM all the way, and I’m more than happy to go along with that.
When it comes to naming a modified version of a component in BEM, the syntax looks like this:
component--modifier
That raises a question about how you then deploy that class name in your HTML. You could just use the modified name:
<element class="component--modifier">
But then in your CSS you’d have to repeat all the style rules for .component
selector inside your rule block for .component--modifier
selector. SASS could you help out here, especially with its “extends” functionality, but the final CSS is still going to containing duplicated rules.
The alternative is to keep your CSS lean and modular, and write your HTML like this:
<element class="component component--modifier">
Now you’ve taken the duplication out of CSS and put into your markup. It looks a little weird. But, on balance, it’s probably the lesser of two evils.
It strikes me that this pattern of always having the base component
class name appear anywhere you have a component--modifier
class name is something that you could programmatically check for. It should be relatively straightforward to write a lint tool that looks in the value of every class
attribute and, if it finds any instances of foo--bar
, checks to make sure that foo
is also in there.
Sounds like it could be a nice little task for Grunt or Gulp. Maybe somebody has already made it.
Mind you, it seems that most lint tools out there are focused very much on enforcing a coding style for CSS and JavaScript—not so much for HTML. I worry that this reflects the mindset of many front-end developers who view CSS and JavaScript as more important than markup …which is a bit odd considering that CSS and JavaScript are subservient to the HTML document that they’re styling and scripting.