BEM naming convention
I like BEM. BEM stands for "Block, Element, Modifier" and it's a way to write your CSS class names in an organized way.
I've recently been at the From the front 2015 conference in Bologna, where Harry Roberts (creator of Inuit) gave a sweet talk about structuring your CSS while keeping your sanity. Throughout the presentation he used the BEM naming convention, which I've also started using recently; it's easy to understand and really helped me make sense of large stylesheets.
So I'm going to sum up BEM in just a few rules, let's start!
Rule number 1: Class all the things #
Always use classes instead of tag names (this is important!). For example, you will have:
.btn {}
.header {}
.main-nav {}
instead of
button {}
header {}
nav.main-nav {}
This is because tags have higher specificity than classes, which would often result in difficulties when needed to change those values down the road. Also, never use IDs.
Rule number 2: Blocks and elements #
Main layout elements are the "Blocks" part of the BEM metodology.
Elements within Blocks are to be marked like follows: .blockname__elementname
Example:
.users-list {}
.users-list__item {}
.users-list__link {}
and the relative html would be:
Rule number 3: Modifiers #
You will obviously have variants of an item. These are the Modifiers (the M in BEM). For example, classes for a default, a small and a large avatar would be named like follows:
.avatar {}
.avatar--small {}
.avatar--large {}
Bonus rule: Javascript #
For elements that work with Javascript, just add a special "js" class which you'll only use for Javascript tricks, without attaching any style to it:
<div class="item -js-cool-trick">
</div>
That's it! It's really easy, just a few simple rules make your code more readable and maintainable. Check out Harry Roberts presentation for lots of additional info and tips.
Photo by Lee Roylland on Unsplash