Have you ever been in a situation whereby, you are trying to style your html elements but you seem not to have the right name for the tags or maybe you feel the class-names you used do not match the html elements?
I think I have found something that will interest you - BEM - Block Element Modifier
Today, I will introduce you to Block Element Modifier, in short form BEM, which is a methodology that helps you to create reusable components and enables efficient code sharing in front-end development.
BEM is a highly useful, powerful, and simple naming convention that makes your front-end code easier to read and understand, easier to work with, easier to scale, more robust and explicit, and a lot more strict.
The BEM approach ensures that everyone who participates in the development of a website works with a single codebase and speaks the same language. Using BEM’s proper naming convention will better prepare you for design changes made to your website.
Now what exactly are these are naming conventions that BEM offers that makes our front-end code become so effective?
Let's dive deep 🚀
In BEM, the B - part which signifies Block, is given a class-name which may consist of letters, digits, and dashes and they can be referred to as the parent elements.
The E - part which stands for Element is a part of the block which have no standalone meaning and every element is semantically tied to its block. It is represented with double underscore.
Lastly, the M stands for Modifier, which flags on blocks or elements. You can use them to change appearance, behavior or state. It is represented with double dash.
Let's recreate this product card component below using BEM syntax:
<div class="product"> <img src="product1.png" alt="Product1" /> <h3 class="product__name">Product1</h3> <p class="product__price>$30.99</p> <button class="product__btn product--color--blue>Blue</button> <button class="product__btn product--color--red>Red</button> <button class="product__btn product--color--black>Black</button> </div>
🚀 The div with the class-name of product is the Block, which contains other elements, that are related to it.
🚀 The product_name, productprice and product_btn are Elements of the parent div, they therefore have the prefix "product" in their classnames, which shows their relationship.
🚀 The product--color--black, product--color--blue and product--color--red are the Modifiers they help when need to add specific styles to each button.
You may also check out an example of BEM syntax:
BEM is only used with classnames. It can tedious when writing the classnames but they will be of great help at the end of the day.