Deluxe Blog Tips About Projects

A shorter BEM version

I’ve been writing CSS with BEM in many projects. It’s a great way to write CSS and helps me a lot in:

  • Not worrying about conflicts of elements’ class names
  • Reducing CSS specificity

However, one thing from BEM that always bothers me is the length of the class. I usually see things like:

.block-name__element-name--modifier-name

I always try to name blocks, elements, and modifiers with one word. It usually works, but sometimes – it doesn’t.

Recently, I just thought about a better and shorter way to write BEM class like this:

.blockName_elementName-modifierName

There are two things:

  • Use camelCase for names, which helps to remove unneeded dashes
  • Use a single underscore and dash to separate words

Compared to the original version of this example, this eliminates 5 characters!

And if you’re using SASS, you can write it as:

.blockName {
    &_elementName {
    }
    &-modifierName {
    }
}

I’ve been using it for a while and haven’t found any issue!

It’s worth noting that if you use this method with other CSS libraries, you still need to care about class names because most libraries use dashes to separate words unless it’s a classless CSS library.