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 {}

and they would be used like so


 

 

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:


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.

Advertisements

2 thoughts on “BEM naming convention

    1. Thanks for your comment.
      I’ve been naming similarly to what you do (only I use underscores to divide blocks from elements), but I’ve noticed that sometime classes become too long… something like users-list__item__container__title__inner etc 😀

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s