85% Discount for all November
Software Development
Computer programming
Coding
Front end
BEM (Block Element Modifier) is a methodology that helps you to create reusable components and code sharing in front-end development.
BEM is a highly useful naming convention that makes your front-end code easier to read and understand, easier to work with, easier to scale and re-use the codebase. Every block .scss will be self-documented at the end.
Sadly, most CSS codebases are sometimes developed without any structure or naming conventions. This leads to an unmaintainable CSS codebase in the long term. The BEM approach ensures that the entire development team of a website works with a single codebase and speaks the same language. Using proper naming will prepare you for the changes in design of the website.
A block is a standalone entity that is meaningful on its own. While blocks can be nested and interact with each other, semantically they remain equal; there is no precedence or hierarchy. Any DOM can be a block which accepts a class name. We use only class names to select a block, not id or tag names. This will help to make no dependency on other blocks/elements on the same page.
An Element is part of a block, and which has no standalone meaning. Any element is semantically tied to its block. CSS class is formed as block name plus two underscores plus element name. means .form__input .Use only class selector to select an element, just like block no ids or tags cannot be considered as element.
A modifier uses to modify block or elements. Use them to change appearance, behavior or state. CSS class is formed as block’s or element’s name plus two dashes: .form-- mod or .form__input--red and .block--color-black with .block--color-red. Spaces in complicated modifiers are replaced by dash.
Let’s explain it with an example
Here we have an HTML from. We can consider it as a block. We can create a separate .scss file only for that block. This will help us to re-use the same component/block wherever we need in our project.
In the above example “form” is a block, 2 “input” tags are elements of the same block, and we have a class called “form__submit--disabled”, it’s a modifier to the element.
Here we wrote css class for the block as “form”, the input element’s classes are “form__input” and “form__submit”.
So in our form.scss we will write this way, then we named an element with prefixing “__” and modifiers are prefixed with “--".
In some organizations the development team take decisions on the naming convention if they need some customization over the BEM structure for themselves. I have seen developers nesting only modifiers. Block and Element will be written without nesting. This helps to find the class easily form the codebase.
You can find a detailed documentation here
You can follow me for more interesting topics and drop a like if you found it informative!
Goodbye have a nice day!
Wednesday, Jul 14, 2021