What__is--BEM?

what is bem (1)

BEM stands for Block Element Modifier - its a popular naming convention used for classes in CSS and HTML, that allows developers to write code that is more structured and easily maintainable by using a predictable way of naming and styling blocks and elements within your code.

So lets see what BEM looks like in action, using the code example below:

<div class="card">
  <img class="card__img”>
  <h5 class="card__title">What is BEM?</h5>
  <p class="card__text">read on to find out!</p>
  <button class="card__btn">Button 1</button>
  <button class="card__btn--blue">Button 2</button>
</div>

Blocks

Blocks are standalone components on your page. You can think of them as the parent. Blocks are named to describe their purpose and are written in lowercase. In the example above, the block is card.

A block can contain many elements and modifiers.

Elements

Elements are parts within a block that serve a specific function within it.

Elements are created by using block class followed by a double underscore and then by describing the relationship between the block and the element.

In the example above, we have an element card__title - the card is our block and the title is the element. Another example is the btn element, card__btn in the card block.

Modifiers

Modifiers can manipulate both blocks and elements , and allow us to change the styling or theme of that element without changing that elements original styling elsewhere.

Modifiers are created by using the block and element, followed by two hyphens and then the modifier name. Again you want to name the modifier something descriptive.

In the example above, we have an element card__btn, and an element with a modifier, card__btn--blue. So our card button may be styled so that its red - however we want to create one button that is blue, thats where the modifier comes in. We can create a style rule using the modifier to make a blue button, without affecting any of the other buttons on our site. Modifiers could also be used to create a dark mode for your site, by modifying the colour palette to work in a dark theme.

So why use BEM?

By using the BEM convention, it should be easier for another developer to read the code and understand what is going on, due to the descriptive naming used. Because of this, we also shouldn't run into conflicts with other CSS names.

BEM also encourages you to structure your code in an orderly fashion, and really comes into its own if you start to use it with SASS, which opens up further ways to use BEM (but thats for another article!)

Do you use BEM for your CSS? Or would you consider using it? Let me know in the comments 😊

Further Reading

BemCSS
Avatar for Kera Cudmore

Written by Kera Cudmore

Junior Software Developer at the Met Office | Code Institute Alumna.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.