DEV Community

Cover image for How To Avoid Long BEM Modifiers
Steffen Pedersen
Steffen Pedersen

Posted on • Updated on

How To Avoid Long BEM Modifiers

Before we begin, we should all get on the same page.

What is BEM? πŸ€”

First of all, BEM is a naming convention. In my opinion, it makes the CSS easier to read and understand. It makes it easier to scale and generally more easy to work with. BEM is an abbreviation of the overall concept. The elements of the structure is Block, Element and Modifier. The description of the examples are inspired by the official guide.

Block

This is a standalone entity that has its own meaning and purpose. The block is .button.

.button {
    display: inline-block;
    padding: 1em;
}
Enter fullscreen mode Exit fullscreen mode

Element

This should be a part of a block that has no standalone meaning and purpose. It should be semantically tied to its block. The element is &__text.

.button {
    display: inline-block;
    padding: 1em;

    &__text {
        font-size: 1em;
        font-weight: 400;
    }
}
Enter fullscreen mode Exit fullscreen mode

Modifier

This should be a flag on a block or an element. Here we are able to change appearance or behavior. The modifier is &--bold.

.button {
    display: inline-block;
    padding: 1em;

    &__text {
        font-size: 1em;
        font-weight: 400;

        &--bold {
            font-weight: 700;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

One of the most important rules is, that you can’t have an element inside an element and you can’t have a modifier inside a modifier.

What is the problem? πŸ€”

With BEM modifiers the naming convention can result in very long selectors. This can damage the readability.

We could make modifiers like this:

.button {
  &.--small {
    height: 2em;
  }
}
Enter fullscreen mode Exit fullscreen mode

In this way we could do this <button class="button --small"></button>.

Instead of this:

.button {
  &--small {
    height: 2em;
  }
}
Enter fullscreen mode Exit fullscreen mode

Which results in longer selectors <button class="c-button c-button--small"></button>.

It would make it easier to get an overview, when reading the outputted code. We just need not to make classes named --modifier outside of a block. That would also be weird.

What do you think? πŸ€”
What could break this idea? πŸ€”

Thank you for your time!

If you liked this, then please ❀️ and follow me on Twitter.

Top comments (1)

Collapse
 
anki247 profile image
Anki Batsukh

RSCSS