The Problem
It is easy to start working with CSS on a small project but as soon as your project starts getting bigger your CSS starts to look messy and maintaining it becomes a huge problem. To solve this problem we use different methodologies like Atomic, OOCSS, SMACSS, BEM, and more from which we will be discussing BEM in this blog.
What is BEM?
BEM stands for BLock Element Modifier which is a naming convention (a set of rules we follow to name things and here the thing is class names) which helps to write efficient and organized CSS code by making it easier to read, understand and scale.
A classname is BEM follows the following syntax:
.block__element--modifier
Some examples of class names using BEM would be:
* .card {}
* .card__title {}
* .card__button--primary {}
A class name in BEM is made up of 3 parts:
1. Block
It is a top-level component that acts like a parent and can exist independently on the page like in the above example .card is a block. Some more examples can be header, navbar, footer etc. A BEM class name always starts with a block like:
.block {}
2. Element
An element is a part of a block and cannot exist independently which means if we remove the block then there will be no meaning left of the element. The element name is connected with the block using two underscores like :
.block__element {}
In the above card component example __image
, __title
, __description
and __button
are all elements connected with the .card
block.
3. Modifier
A modifier acts like a flag that we can use on our blocks or elements to create a different version of them or to differentiate them with their regular version. The modifier name is connected with the block or element like :
.block--modifier {}
.block__element--modifier {}
In our above example, we have the --primary
and --secondary
modifiers which are being used to differentiate between a primary button and a secondary button.
Benefits
- It provides a great structure to your CSS code which makes the code easy to read and understand.
- As BEM has a unique style to create CSS class names, we won't run into conflicts with other class names.
- BEM follows a modular approach that helps to create independent components that can easily be reused in the same project or can also be be used in another project.
Conclusion
In the end, I would highly recommend using BEM for your next project. At the start, it might feel like a lot of extra work to use such big class names for your CSS but all this extra work will definitely help you a lot as your project gets bigger and your future self will thank you for all the extra work you did.
Top comments (3)
Great post khusharth, keep it up 👍👍
Thanks a lot, Viral :)
Wish I knew this while starting out 👍