Have you ever been in a situation when you need to do a small change in a project that you haven’t been working on for 6 months and you didn’t know where to start modifying your stylesheet? All the classes and identifiers sound familiar but you have to spend a good while looking at the markup to understand what’s exactly going on. Well, we’ve all been there.

BEM to the rescue

BEM is an abbreviation for Block, Element, Modifier, a methodology created by folks at Yandex, which is meant to give your stylesheets a little bit of architecture and common structure.

BEM methodology follows the pattern below:

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

Everything which is semantically independent and can be considered as a separate whole should be a block. It will be a sidebar, form element, button and all the components that make sense on their own.
As an element we should count every part of markup that is a composite part of a block and shouldn’t be used separately. So think about element like components which depend on the blocks.
Modifier describes a state or particular behaviour of given block.

Example use

Consider the following HTML markup:


1
2
3
4
5
6
7
8
9
10
11
<a class="button">
  Buy for <span class="button__price">£5</span>
</a>

<a class="button button--success">
  Buy for <span class="button__price">£5</span>
</a>

<a class="button button--error">
  Buy for <span class="button__price">£5</span>
</a>

And the CSS:

.button {
 font-family: Arial, Helvetica, sans-serif;
 display: inline-block;
 font-size: 14px;
 color: #CFD8DC;
 padding: 5px 10px;
 border: 1px solid transparent;
 border-radius: 5px;
 background: #536DFE;
}

.button__price {
 color: #FFFFFF;
 font-size: 16px;
 font-weight: bolder;
}

.button--success {
 background: #00796B;
}

.button--error {
 color: #FFFFFF;
 background: #FF5252;
}

In the example above button is a block which has two modifiers: success and error, and price is it’s element. We can say that just by looking at the styles, there’s no need for looking at HTML markup.

See more examples, including real-life ones in the official documentation.

Which principles and methodologies are you following while writing your code? Let me know in comments ?

LEAVE A REPLY

Please enter your comment!
Please enter your name here