albert105 albert105 - 1 year ago 56
HTML Question

Can block elements be dependent on block modifiers in BEM?

What's common use when using BEM? I can't find this anywhere..
In SCSS, can I make

.block__element dependent
of the modifier of its block?

For example, say
is always white but only when
has the modifier

<div class="header">
<div class="header__text">
Default color is black

<div class="header header--bgblue">
<div class="header__text">
I want this to be white because it's inside header--bgblue

Or is it best practice to make seperate element modifiers for each element?

<div class="header header--blue">
<div class="header__text header__text--white">
I want this to be white because it's inside header--bgblue

In this case it's a small effort but when there are more dependencies (e.g. more elements involved), is this the way to go?

tzi tzi
Answer Source

There is no absolute rules with BEM, but it's a really good question!

In pure theorical BEM, you should prefer the .header__text--white for two reasons:

  • It creates more possibility, so it prevents code duplication
  • It allows you to keep your selector with only one class

But personnaly, I often choose the .header--bgblue .header__text:

  • Block modifiers are simpler than element modifiers. When the second creates possibility, it also creates complexity and make hard to predictate what the block render will be without reading the full markup.
  • It promotes consistency. If the text should always be white when the background is blue, it could be nice to take a shortcurt in the best practices to explicit that.
  • If you have to restyle every elements for a block modifier, it makes markup and styles unreadable.

To sum up, it's your choice! And you should adapt it to the use case ;)