CodeNewbie Community 🌱

Pachi Parra
Pachi Parra

Posted on

What is BEM and why use it to name your HTML classes!

Good day!
Today I will be talking about one of the tools I use on my web development projects that makes me code prettier and my life easier: BEM!

What is BEM?

BEM (Block, Element, Modifier) is a naming convention for classes in HTML and CSS what was developed by Yandex.
Basically, it is a methodology to help you understand better what is going on between you HTML and CSS and styling it better.

Why use BEM?

You don't have to, of course. So why use it?

  • BEM gives some structure to you code, it is quite simple to use.
  • It makes easier to style your HTML elements and read it.
  • It helps to avoid style conflicts,
  • Consistency!!!

So, how do I use it?

Okay, let's go to the fun part!

<div class="hero">
   <img class="hero__img">

<div class="main">
    <h1 class="main__title">
    <p class="main__text"></p> 
    <p class="main__text-special"></p>  
    <p class="main__text"></p>

Enter fullscreen mode Exit fullscreen mode

So here, we have a very simple piece of code.
The < div > is out block. The block element only needs one nice name, and in this case we have hero and main.

The elements are the item we are putting inside de block. They are part of the block, so they first get the blocks name.
Their second name, should be a description of what it is. Here we have:
"main__text", "main__title" and "hero__img".

While you will use this one probably a little less than the first two, modifiers are important. They tell you that some item may be special yet, still be an element. Our second < p > is called "main___ text-special".
Maybe this one will have a bigger font, of a brighter background. Who knows?
But while it is still a "main__ text", adding the "-special" tells that it will have a differential.

What about those __ and - ???

It is just the way BEM works.
Blocks just need a name, Elements need the block name, the __ and them the elements name, and the modifiers need the above and a - followed by the modifiers name.


I tried to keep this explanation as code newbie as possible and I hope it helps.
BEM is a very helpful methodology, and the few times I don't use it, you bet I will have some style heritage issue lol

*P.S.If you would like something more complete, Smashing Magazine has a great post for Beginners! *

Top comments (0)