3

What is the more appropriate approach when using BEM ? Are we allowed to not add extra classes to elements and style the elements themselves

<section class="news-section">
  <a>link</a>
</section>


.news-section {
  a {
    color: blue;
  }

}

Or do we have to add extra classes to all elements and style those classes?

<section class="news-section">
  <a class="news-section_link">link</a>
</section>

.news-section {
  &_link {
    color: blue;
  }

}
Paran0a
  • 3,359
  • 3
  • 23
  • 48

4 Answers4

3

Are we allowed to not add extra classes to elements and style the elements themselves

No.

With BEM, you have to always use CSS classes:

In HTML, BEM entities are represented by the class attribute. (bem.info)

In return for this rigidity, BEM will bring you :

  • Scalability, because blocks can be nested without limit;
  • Flexibility, because CSS selectors are loosely coupled with HTML tags.
Paleo
  • 21,831
  • 4
  • 65
  • 76
2

You should definitely add extra classes to style elements like links. It's the same situation as when you add styles to buttons header__btn or images use-profile__img

It is never bad to add additional classes and they make code expandable in the future. Imagine a situation where you would like to add more elements inside this <a> tag. You wouldn't code it like this news-section__a__link-header right?

Important: you shouldn't target elements 2 levels down with BEM as it's block__element-modifier, not block__element__element--modifier :)

BEM is pretty well explained here

Kacper Cieluch
  • 437
  • 3
  • 16
  • Agree with your answer, however the toptal article is a bad example. What the hell is this `class=”header__search-from__input”`? I don't understand why people link to examples from all kind of sources, but not the original website of the creators: https://en.bem.info/methodology/naming-convention/#naming-rules – Nikolay Mihaylov Apr 18 '18 at 19:53
2

To add to the existing answers, yes avoid using specificity to style items unless absolutly needed (CMS wysiwyg content for example), so your second code block it correct BEM

However in your specific example, all you are setting is a color, and you probably have other items you want the same color right?

So i probably makes more sense to use a utility class for that:

<section class="news-section">
  <a class="u-txt-blue">link</a>
  <p class="news-section__title">...</p>
</section>

.news-section {
  ...
  &__title{
     ...
  }
}
//utilities.scss

.u-txt-blue{
    color: blue;
}
Steve
  • 20,703
  • 5
  • 41
  • 67
1

Add classes to all the elements so as not to tie your styling of your components to your HTML structure.

In your example your first example, the new-section__link will have to be an anchor element, in the second it can be any type of element which is a lot more powerful and flexible.

Danny
  • 1,083
  • 2
  • 8
  • 12