Naming CSS classes with BEM.

Tue, 2 January 2018
2 min read

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>

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.

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 class="button-hood">
  <!-- 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>