How to write code à la B.E.M. convention

.block__element — modifier (B.E.M.) is a class naming system that, if used effectively, makes you code more consistent, organized and easy to read.

For BEM, it is best practice to use kebab case rather than camel case. Kebab case makes your code less confusing, especially when you include any JS later.

Blocks

Blocks are pieces of code that are going to be reused and don’t depend on other components. It is the highest level of any individual component and it’s written with no other syntax:

<div class=“post” >

Some examples of blocks on a web page would be a navigation bar, a header, a footer, a gallery, a hero image, a modal, or a slide in menu.


Elements

An element is a composite piece of a block that would never be used separately. Not all blocks have elements. But all elements must be nested inside of blocks and will never exist outside the context of its parent element. For instance, nested within the navigation, a UL and LI is an element.

Elements are always prefixed by the name of the block they come from and have two underscores. An element’s name should always describe what it is, not what it looks like.

<div class=“post__heading’>

<div class=“post__author’>

<div class=“post__content’>


Modifiers

A modifier describes the appearance, state or behaviour of a block element.

Use two dashes to denote a modifier.

<div class=“post__heading- -small’>

<div class=“post__heading- -large>

When naming the modifier, ask yourself, how is this element different from others?


When first using BEM, most people complain that it makes code excessively long and gruelling to type out. As a general rule, try not to get more than three levels deep.

“The trick with BEM is knowing when something falls into a relevant category. Just because something happens to live inside a block it doesn’t always mean is is actually a BEM element. In the case of our site logo it lives in the .header purely coincidentally; it could just as easily be in our sidebar or footer” — Nicolas Gallagher