5 Minute Guide to BEM

Your busy. You’ve got stuff to do. Here’s BEM in 5 minutes.

What is BEM?

BEM is an acronym for Block Element Modifier and it is a naming convention for organising your CSS. Without it, or something like it, CSS can become an unstructured mess that is hard to maintain.

Advantages of BEM

It has a number of advantages:

Scope in this case, means that we can make our CSS more modular by using unique class names, and helps to avoid CSS inheritance. Specificity on the other hand is the idea that sometimes CSS rules will clash - e.g. 2 classes want to be applied to the same HTML element - and therefore a scoring system comes into play. Who wins? Most developers are forced to use !important to guarantee a winner.

Disadvantages of BEM

Some disadvantages of using this technique has been aired.

  • Some think it will bloat the size of the CSS files (countered by using minification and compression)
  • It could make your HTML look ugly (a personal thing and besides, no-one sees the HTML usually anyway).

Using BEM

The three components of BEM - Block, Element and Modifier can be
thought of as follows:

  • Block - any HTML element that can accept a class to modify it. E.g. DIV, P or INPUT
  • Element - an aspect of that block, which relates directly to one specific block. E.g. price in an input field, or the search part of an input box
  • Modifier - something which alters the state of the element. E.g. adding a red box around the search box, or changing the font of a price.

Naming Convention

The naming convention can be illustrated with this example:

1
2
3
4
5
6
7
8
// Blocks are named as standard CSS classes
.block {}
// Elements declared with 2 underscores, after block
.block__element {}
// Modifiers declared with 2 dashes, after block or after element
.block--modifier {}
// element and modifier together
.block__element--modifier {}

An Example

If we take a specific example, let’s show a rule for an imaginary input box, which accepts a currency.

1
2
3
.order-total__price--error {
// add a red box around HTML element
}

Here, our block would be named order-total and would be applied (most probably) to an INPUT element in HTML. price is the part of our BEM element that is tied to the block, and has no meaning on its own, making it our element. Lastly, error is our modifier, and alters how that element is presented.

Finding out More

If you would like to learn more about BEM, see their website.


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com