BEM! Tackle your growing CSS with a Pattern that just works

Alexander Rühle, March 20, 2017 10:40

As i worked on a big project for my job, we came to the conclusion, that just using the Twitter Bootstrap CSS Framework with some view specific CSS code is not enough.

This all resulted in some big assets folders with a huge load of files which prevented any kind of good maintainability. BEM, meaning Block, Element, Modifier, is a front-end methodology developed at Yandex.

It is important to note that the naming techniques covered in this post are not the original BEM ones, but are altered versions that I much prefer. Whatever actual notation is used, they are all based on the same BEM principles.

.block {}
.block__element {}
.block--modifier {}
.block__element--modifier {}
.long_block_name {}

There are basically three groups:

  • .block: the root block component
  • .block__element: a part of a block component
  • .block--modifier: a variant, modification, extension of a component block (can also be aplied to an element)

Elements are delimited by two underscores. Modifiers are delimited by 2 hyphens. Long block names are delimited by one underscore. This has the advantage that you can select the classes better by a double click.

The whole point is to improve readability by other developers, so you can tell what the markup is doing by the name alone.

Let me give an example. You probably all know the .media element from different kinds of CSS Frameworks.

.media {}
.media__img {}
.media__img--right {}
.media__body {}


<div class="media">
  <img src="image.png" class="media__img media__img--right" alt="awesome image"/>
  <div class="media__body">
    <h2><!-- title --></h2>
    <p class="lead"><!-- some lead text --></p>

Now we can see, that .media is a block and .media__img is a element with a modification or extension .media__img--right. The class .lead has nothing to do with our component. This is very helpful.