Codementor Events

NAMING CSS CLASSES WITH BEM

Published Jul 04, 2018

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>

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>

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>

Also you can watch video here about BEM

Discover and read more posts from Frugence Fidel
get started
post commentsBe the first to share your opinion
Show more replies