/blog/articles/

Making use of the BEM naming system

I'm a big fan of the BEM way of writing CSS classes. I think besides from sometimes having a somewhat long class name it only has benefits. The biggest is it's simplicity and clear structure.

If you've never heard of BEM, here is a short introduction. BEM is short for Block Element Modifier and this is a simple example:

<nav class="site-nav">
  <a class="site-nav__item" href="#">Home</a>
  <a class="site-nav__item site-nav__item--active" href="#">About</a>
  <a class="site-nav__item" href="#">Contact</a>
</nav>

In this example site-nav is the Block, site-navitem is the Element and site-navitem--active is the modifier. Styling with these class selectors brings great flexibility because you could easily change the HTML elements, keep the classes and the CSS would keep working.

A developer not familiar with the project will also be easily able to understand the system and can get an impression of the HTML structure from simply looking at the CSS.

Furthermore it helps and encourages to write portable modules, which is what brings great flexibility.

.site-nav {
  margin-bottom: 20px;
  max-width: 300px;
}

.site-nav__item {
  display: inline-block;
  color: #000;
}

.site-nav__item--active {
  border-bottom: 1px solid;
}

There is more to it, but that's enough to get the idea of the system. If you want to read more on the topic, Harry Roberts has a great detailed write-up.

Because the BEM naming system worked so well for me for CSS classes and I'm a big fan of structuring things in a simple, yet powerful way, I started using it elsewhere, too. I think SCSS variables are a great example for that. I transitioned into naming them this way:

$grey: #a2a2a2;
$grey__dark: #535353;
$grey__dark--hover: #b2b2b2;

$header__height: 50px;
$header__height--fixed: 20px;

I also use it for file naming for example for images:

icon__checkmark.svg

icon__checkmark--active.svg

header__bg.jpg

header__logo.png

header__logo--small.png

I'm sure there are other areas where we could put the BEM way of naming things to good use and increase structure and ease of use. I'm curious to hear your ideas.

Hit me up on Twitter @_martinwolf.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.