DEV Community

Sanjeev Sharma
Sanjeev Sharma

Posted on

Keeping your sanity with BEM CSS

Hi!
So, you're working on a huge project? And you go crazy over css when it leaks? You find it hard to manage? You have come to the right place. This article is for you! 😉

What is BEM?

It's not a library! You don't have have to install anything to start using BEM.
BEM stands for Block Element Modifier. Block Element Modifier is a methodology that helps you to create reusable components and code sharing in front-end development. It's basically a naming convention that makes your code more readable, scaleable, robust, and strict.

Are there any other methodologies like this? Yes! like OOCSS, SUITCSS, Atomic, etc.

How to use BEM?

Let's go over these terms one by one.

Block

Any standalone entity that is meaningful on its own. For example - header, hero, menu and footer on a website.

Element

A part of a block that has no standalone meaning and is semantically tied to its block. For example - menu items inside menu(Block).

Modifier

A flag on a block or element. Use them to change appearance or behavior. For example - hover state on our menu items(Elements) inside menu(Block).

Alt Text

In this image, Header and Menu are Blocks. Menu items are Elements. When you hover over menu items, you can change appearance using Modifiers. Enough talk, let's code now.

Example

It's recommended to avoid using tag names in css and use class names instead.

The pattern followed in CSS is: Block__Element--Modifier.
Block (two underscores) Element (two hyphens) Modifier.

Blocks can have modifiers too. In that case class name would be - Block--Modifier

I know it looks a bit tedious when using CSS, but it works wonders with SASS. There's significant improvement in readability.

Let's see same example with SASS.

I recently got to use BEM in one of the open source projects I have been working on. I really love how clean and maintainable it is. I hope this urges you to try it at least once.

Thank you for reading! 🙏

You can connect with me on Twitter and LinkedIn. 👋

Top comments (2)

Collapse
 
blossom profile image
Blossom Babs

I absolutely love BEM. Been using it with my scss and it makes for a more readable codebase. Awesome!

Collapse
 
bawa_geek profile image
Lakh Bawa • Edited

I like bem, using it for quite some time. but now here comes the utility first approach. which I believe should be preferred for new projects.