Quick notes on BEM (Block Element Modifier) syntax in CSS

What is it?

How to use it

.block {
}
.block__element {
}
.block--modifier {
}

For example, in JSX:

<div
  className={`block ${isSelected ? "block--selected" : ""} ${
    warning ? "block--warning" : ""
  }`}
>
  <div className="block__element"></div>
</div>

A โ€˜real worldโ€™ example:

.person {
}
.person__hand {
}
.person--male {
}
.person--male__hand {
}
.person__hand--left {
}

A real world example

Before BEM

.site-search {
}
.site-search.full {
}
.site-search .field {
}
<form class="site-search full">
  <input type="text" class="field" />
  <input type="Submit" value="Search" class="button" />
</form>

With BEM

.site-search {
} /* Block */
.site-search__field {
} /* Element */
.site-search--full {
} /* Modifier */

or

.site-search {
  /* Block */
  &__field {
  } /* Element */
  &--full {
  } /* Modifier */
}
<!-- Notice that a modified element gets both the base block class and the modifier class -->
<form class="site-search  site-search--full">
  <input type="text" class="site-search__field" />
  <input type="Submit" value="Search" class="site-search__button" />
</form>

Pros and cons

When mixed with global styles like the below, itโ€™s flexible, but a new developer would need to know these helpers existed to use them.

.noBreakText {
  white-space: nowrap;
}
.upperCase {
  text-transform: uppercase;
}

e.g.

<div class="header">
  <div class="logo"></div>
</div>

or

<div class="header">
  <div class="header__logo"></div>
</div>

Resources