DEV Community

Frugence Fidel
Frugence Fidel

Posted on • Updated on

Naming CSS classes with BEM

This post is originally posted to my blog.

BEM - Block Elemet Modifier is the way of naming CSS classes so that they can be more meaningful and reusable.

BEM help to avoid name collisions and reduce the pain of modifying CSS classes when changes are need to be made. As you known when working with large project, modifying a single CSS class may lead to dozens of affected pages. BEM help to avoid all those problems.

Let me explain what I known about BEM:

B - Block

Block is an independent, reusable and standalone part of design. Blocks can be nested in each other.

  <!-- hero block -->
  <section class="hero">
    <!-- btn block -->
    <a href="#" class="btn">Click Me!!</a>
  </section>
Enter fullscreen mode Exit fullscreen mode

E - Element

Element belongs to a block and can not standalone. Simply it can not be used outside of the block that it belongs to. Elements can be nested inside each other. CSS class is formed as block name plus two underscores plus element name.

  <!-- hero block -->
  <div class="hero">
    <!-- content element belongs to hero block -->
    <div class="hero__content">

      <!-- title element belongs to hero block -->
      <h1 class="hero__title">I'm main title</h1>

      <!-- text element belongs to hero block -->
      <p class="hero__text">Cupiditate dolores iste reiciendis ea non iure est.</p>
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

M - Modifier

Modifiers are used to change the default behavior or state of an element or block. Also Modifier are not standalone, mean they can not used outside of blocks that they belongs to. They show what size, how difference or how does they behave from default ones. CSS class is formed as block name plus two 'minus sign' plus element name.

  <div>
    <!-- default btn block -->
    <a href="#" class="btn">I'm OG</a>

    <!-- btn block modified by red modifer -->
    <a href="#" class="btn btn--red">I'm red</a>

    <!-- btn block modified by red and large modifer -->
    <a href="#" class="btn btn--red btn--large">I'm red and large</a>
  </div>
Enter fullscreen mode Exit fullscreen mode

Also you can watch video here about BEM

Top comments (2)

Collapse
 
mrenzidev profile image
Marco Renzi

So you have other elements inside hero_content.
Should i use hero
content_title?

Collapse
 
frugencefidel profile image
Frugence Fidel

If hero_content is block, then the element inside will be like this hero_content__title