Search code examples
csscss-selectorsbem

What is BEM methodology?


I recently heard about BEM methodology.

  • What exactly is the use of BEM methodology ?
  • In what way does BEM make our work easier ?
  • Is it a good practice to use BEM ?

Solution

  • BEM is a naming methodology. It stands for Block Element Modifier and it's aim is to facilitate modularity and make styles and classes a lot easier to maintain.

    It's not easy to explain it in a reply, but I can give you the basic idea.

    So if you're thinking of a menu, then the whole element / component structure would be:

    Block: menu Element: item Modifier(s): horizontal, vertical

    And by following standard BEM conventions, you would write something like this in CSS:

    html,
    body {
      height: 100%;
    }
    
    .menu {
      display: block;
    }
    
    .menu__item {
      display: inline-block;
      line-height: 30px;
      width: 100px;
    }
    
    .menu--horizontal {
      width: 100%;
      height: 30px;
    }
    
    .menu--vertical {
      width: 100px;
      height: 100%;
    }
    
    .menu--horizontal .menu__item {
      border-right: 1px solid #e5e5e5;
      text-align: center;
    }
    
    .menu--vertical .menu__item {
      border-bottom: 1px solid #e5e5e5;
      text-align: left;
    }
    <div class="menu menu--horizontal">
      <div class="menu__item">Home</div>
      <div class="menu__item">About</div>
      <div class="menu__item">Contact</div>
    </div>

    As you see from the code, the elements are separated from the block with 2 underscores and modifiers are separated with 2 dashes.

    Now if you change the modifier on the menu from --horizontal to --vertical, the specific modifier styles will be picked up for both the block and the element inside.

    This should be a basic example, but it should give you an idea of how powerful this methodology is, because it allows splitting any component into these basic block-element-modifier structures, making everything a breeze to maintain.

    Also writing this using a precompiler like SASS makes it even easier (I won't go into details, but to give you an idea):

    .menu {
      display: block;
    
      &__item {
        display: inline-block;
        line-height: 30px;
        width: 100px;
      }
    
      &--horizontal {
        width: 100%;
        height: 30px;
      }
    
      &--vertical {
        width: 100px;
        height: 100%;
      }
    }
    

    It's a methodology that's scalable, so it can be used for either small projects or large projects.

    It takes a bit of getting used to, so doing some research and playing with it on a small scale project would be a good starting point.

    Here's a use case, if you want to see it in used in a real project https://m.alphasights.com/how-we-use-bem-to-modularise-our-css-82a0c39463b0#.2uvxts71f

    Hope it helps :)