Writing Reusable and Modular CSS with BEM


What is BEM?

BEM is a CSS naming convention. Its name is an abbreviation for Block, Element, Modifier. In short, it’s a simple way to add some sanity to your CSS codebase.

Syntactically it looks like this

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

Let’s add some context with a UI component. The entirety of that component is the block. Any unique piece inside that component is an element. A specific style or behavior of an element or the block itself is a modifier.

Now let’s take a classic UI component like navigation and break it down.

.navigation {
  width: 800px;
  background-color: #f8f8fa;
  color: #282c35;
}

.navigation--dark-theme {
  background-color: #282c35;
  color: #f8f8fa;
}

.navigation__logo {
  width: 200px;
}

.navigation__tab {
  width: 100px;
}

.navigation__tab--active {
  color: salmon;
  text-decoration: underline;
}

If you’re using a preprocessor like SASS I’m sure you have already considered how well with works with nesting.

Block

.navigation is the block.

Element

.navigation__logo and .navigation__tab are elements.

Modifier

.navigation--dark-theme and .navigation__tab--active are modifiers.

What does BEM solve?

Right now, you’re probably only thinking about the outlandish class names. Albeit unattractive, there are massive benefits to it. So let’s look at some CSS issues BEM solves.

Specificity

Specificity is a fundamental characteristic of CSS and can sometimes cause a lot of issues. Lack of specificity can cause unwanted inheritance, BEM employs verbose singular class names that prevent this from happening, and although not too significant, a performance boost coincides with this.

Reusability

BEM allows you to compartmentalise your code. This lets you reuse CSS modules across a wide array of components, minimising the amount of code you’ll need to maintain. On top of this, it naturally creates a smaller CSS codebase, saving some ever important milliseconds on page load.

Readability

The structure of BEM code is extremely clear. You can look at a single UI component and understand what’s going on in an instant. Not only will your co-workers love you but you’ll be thanking yourself when it comes to refactoring.

Take Away

By now you have seen the numerous benefits of adopting BEM, and the common CSS issues it can provide a solution to.

It’s easy to write CSS, but it’s not easy to write good CSS. BEM is a simple reminder to think about the CSS you are writing, which in itself can have huge benefits.

To see the use of BEM in my code, have a look at this CSS codebase - https://goo.gl/EBuxjT.

Let's stay connected. Join our monthly newsletter to receive updates on events, training, and helpful articles from our team.