3

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 .header__text is always white but only when .header has the modifier .header--bgblue.

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

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

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
    </div>
</div>

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
  • 8,719
  • 2
  • 25
  • 45
albert105
  • 119
  • 1
  • 2
  • 8

1 Answers1

1

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 ;)

tzi
  • 8,719
  • 2
  • 25
  • 45
  • Thanks for your advice. When I choose the latter, what's the SCSS way of doing this? This is what I have now: .header { &--bgblue{ ... }; &__text{ ... } }; How can I combine the two? Or do I have to do this outside the SCSS nested notation? – albert105 Apr 19 '16 at 13:22
  • Ok, I can do it like this: .header { &--bgblue{ .header__text { color: #fff } }; &__text{ color: #000 } }; Kinda ugly and messing up the scss structure but hey.. it does the job. – albert105 Apr 19 '16 at 13:31