5

Let's say I have a structure like this:

<article class="product">
  <header class="product__header">
    <h1 class="product__headline">Headline</h1>
    <img class="product__hero" src="" alt="">
  </header>

  <p class="product__description">Content</p>
</article>

As the Block element article brings all the styles it needs by default, it actually doesn't have any CSS. So I'm not defining it in the CSS like this, because it only clutters the styles:

.product { }

But I'm unsure about the HTML. Should it be

<article class="product"></article>

… anyways or simply …

<article></article>

… as there are no styles attached?

What is the right thing to do when usin BEM?

lampshade
  • 2,470
  • 3
  • 36
  • 74
  • i think you have to add the class attribute anyway, however you can use a javascript that gives an empty class attribute to every element that doesn't have it – Giuppox Oct 30 '20 at 11:08

3 Answers3

6

As I understand it, the idea with BEM is to use a standard and have a markup ready for any present or future CSS, so you would always include the class, even if you don't use it right now.

Another good reason is that the parent class improves readability and order for anyone looking at the markup. I would even suggest you to include the class in your CSS and left it blank, functioning almost like a subtitle, with the potential to be useful later on.

Finally, BEM recommends against nesting elements in the stylesheet, which means preferring the use of classes even in the smallest children (like a strong tag inside a p). Seems natural, then, to have a class in the parent as well.

alotropico
  • 1,904
  • 3
  • 16
  • 24
  • 2
    Hm, I'm not sure about leaving the empty class definitions in the CSS. I have them but as comments. Otherwise the parser would raise a warning, that there's something cluttering the source. But I guess I'll keep the classes in the HTML to make the structure visible for now. – lampshade Oct 30 '20 at 10:20
  • 1
    Regarding your last point and readability, while BEM does recommend against nested selectors, sometimes it's more readable to use nested selectors in order to exclude repetitive class names (overkill) in the markup for simple cases like when you target
  • s within
      or

      s within

      . [Nesting is appropriate if you need to change the styles of elements **relative to the state of the block** or the theme set.](https://en.bem.info/methodology/css/#nested-selectors) Though, I don't agree with BEM's example of nesting a class selector within a class selector as this voids my above point.
  • – z2lai Mar 18 '23 at 19:50