Today I wanted to write a short blog to explain BEM and it’s benefits.

What is BEM?

BEM (Block Element Modifier) is a naming styleguide that helps you to create reusable components and code sharing in front-end development.

Why do I care about that?

Creating reusable code will allow you to develop future features and modify existing ones with much more ease. Furthermore if anyone has to dip into your code they will have an easier time figuring out what they are looking at and how your class names work.

So now let’s move onto the how it works.

Block

The block is a class name that defines the standalone entity. In this example I’ll use .banner

<div class="banner"></div>

Element

The element is for parts of your block that do not have any meaning on their own. So let’s say our banner has a heading inside of it. We would want to name it .banner__heading

<div class="banner">
  <h1 class="banner__heading"></h1>
</div>

CSS

Finally, you’ll want to make sure your CSS is following along with BEM rules. The idea is to make easy to modify/replace style rules. An example of the final result here would be

.banner {
  width: 100%;
  max-width: 60%;
}

.banner--full-width {
  max-width: 100%;
}

.banner__heading {
  font-size: 3em;
  font-weight: bold;
}

As you can see from this small example, having the CSS separated as such helps make our code easy to modify with little worry of what sort of echo effect will occur.

Modifier

These are used for flags on blocks or elements to describe behavior, states and appearances. Let’s say our banner has a full-width flag .banner--full-width

<div class="banner banner--full-width">
  <h1 class="banner__heading"></h1>
</div>

Little extras

If you are working in an environment where third-party applications will also be adding features or modifying existing ones you can also consider prefixing your elements with a unique tag. This will help avoid any conflicts.

<div class="mtu-banner mtu-banner--full-width">
  <h1 class="mtu-banner__heading"></h1>
</div>

Summary

I hope this helps explain how BEM works and I hope you can see why it will help you and your teams workflow. If you want find out more on this subject check out getbem.com