DEV Community

Discussion on: What is BEM and why use it to name your HTML classes!

Collapse
 
goodevilgenius profile image
Dan Jones

I've seen this many times before, and still don't understand why this is at all useful.

If I want to target the hero__img img, I'd have to select it with .hero__img. But I could leave out the class, and target it with .hero img as well. Or even .hero > img for higher specificity.

And the modifiers make less sense to me.

If I mark the second div like this:

<div class="main">
    <h1 class="title">
    <p class="text"></p> 
    <p class="text special"></p>  
    <p class="text"></p>
</div>
Enter fullscreen mode Exit fullscreen mode

Then I can select all three ps with just .main .text, and then add in additional styles for special by selecting .main .text.special.

But with this way, if I want common styles between all three p tags, I have to select .main__text, .main__text-special, and then a second one for .main__text-special. This seems a lot less efficient, and completely goes against the intended design of CSS selectors.

Collapse
 
damsalem profile image
Dani Amsalem • Edited

The reason BEM is great is because CSS is read right to left by your browser. Check out this two paragraph article css-tricks.com/why-browsers-read-s...

I also was struggling trying to understand why BEM, but understanding the right-left concept helped. Essentially, all elements are given a class and because they are specific to that item or type of item, your browser doesn't have to do as much work to apply styles.

In addition, I use the SCSS preprocessor and BEM is a-mazing when the two are combined.

Instead of repeating my selectors like this:

.main {}
.main__title {}
.main__text {}
.main__text-special {}
Enter fullscreen mode Exit fullscreen mode

I can nest them using the ampersand selector:

.main {
  &__title {}
  &__text {}
  &__text-special {}
}
Enter fullscreen mode Exit fullscreen mode

If you want some more detailed breakdowns of BEM, I suggest checking out Kevin Powell's YouTube video explaining it youtube.com/watch?v=SLjHSVwXYq4