Introduction to BEM

Alex Ferreira
3 min readJun 25, 2019

Note: If you’re not a fan of reading, you can find a video tutorial I made explaining this whole BEM business at the bottom of this page.

The Block Element Modifier methodology (aka ‘BEM’) is a name convention for HTML and CSS that aims to help developers understand the relationship between the markup and the style in a certain project.

Let’s talk Blocks

When you have a website, it’s useful to divide it into blocks — like a search block, a logo block or an authentication block, for example.

Blocks can be simple or compound (when it contains nested blocks) and can me moved around on a page, moved between different pages or projects, and instances of the same block can be created.

What about Elements?

Elements are functional parts inside a block and are context-dependent, meaning they can’t exist outside a block.

Modifying

Modifiers’ purpose is to change the appearance or even the behavior of a block or element. Modifiers are also optional.
Modifiers work a bit like HTML attributes: you can have four instances of the same block and use a modifier to change the appearance or behavior on one of them.

Choosing names

The main idea of the naming convention is to make the CSS selectors names as clear and informative as possible. We could simply write menuitemblue as a selector to a DOM element. Obviously that would be a bit hard to read so we can just camel case it (menuItemBlue) or separate the words by a hyphen (menu-item-blue).
Looking at this example we can assume menu is a block, item an element and blue its modifier. However, real-life examples are usually not as straightforward, and that’s where the BEM naming convention comes in useful.
The BEM CSS selector naming convention consists in using only lowercase characters; and separating individual words with one hyphen (-).
When writing elements names we should always separate them by a double underscore (__).
Modifiers should be separated by a single underscore or, if you prefer Harry Roberts’ alterntive style, a double hyphen ( — ).

<nav class="menu">
<ul class="menu__list">
<li class="menu__item"><a>Tab 1</a></li>
<li class="menu__item"><a>Tab 2</a></li>
<li class="menu__item menu__item--active"><a>Tab 3</a></li>
<li class="menu__item"><a>Tab 4</a></li>
</ul>
</nav>

Note that on our third <li>, because we want to use a modifier to change its appearance, we also have to write the block that is affected by the modifier.

The BEM methodology was created by an IT company named Yandex and they have some cool documentation and tutorials regarding BEM if you’re interested in deepen your understanding of this methodology.

--

--

Alex Ferreira

Front End Web Developer @hotjar and owner of a cat named Ubuntu