Search code examples
cssnaming-conventionsnamingconventionsbem

Trouble naming children of BEM modifiers


So I have the following BEM classes:

.block
.block--modified
.block__child

Now from what I have seen most people would name the child of the modified .block like so:

.block--modified__child

Which I get that makes sense, but is there a reason you could not name it like this:

.block__child--modified

I think this looks better and keeps the modification more isolated / explicit, I also like this because then you can have multiple modified children that are not dependant on the parent being modified i.e

We can have a .block and .block .block--modified elements.

And both can have .block__child and .block__child--modified which still follows the naming convention but makes the child elements (modified or not) more flexible.

For a better example say I have the following classes:

.alert
.alert--warning
.alert--urgent

.alert__call-to-action
.alert__call-to-action--warning

And I want to layout my HTML as follows:

<div class="alert">
    <button class="alert__call-to-action">
        Action! (No Modifier)
    </button>
</div>

<div class="alert alert-warning">
    <button class="alert__call-to-action alert__call-to-action--warning">
        Action! (Warning Modifier)
    </button>
</div>

<div class="alert alert-urgent">
    <button class="alert__call-to-action alert__call-to-action--warning">
        Action! (Warning Modifier)
    </button>
</div>

So you will see I want to re-use the .alert__call-to-action--warning modifier twice in the .alert--warning and .alert--urgent because for what ever reason the styling is the same. Does this make sense from what I can see it makes the modifiers much more usable?

Is there a reason we don't do this? Sorry if there is a better place to post about this please let me know.


Solution

  • Actually BEM methodology says you shouldn't reflect block modifiers in elements naming. Use nesting for such occasions.

    See second paragraph of https://en.bem.info/faq/#why-should-i-avoid-using-nested-selectors

    That's important because:

    1. There can be quite a lot of modifiers on same block/element
    2. Modifiers represent state of a block/element which may be changed in runtime with JS.

    So if you go with modifiers reflected in elements naming it'd be much harder to handle.