getbem.github.io icon indicating copy to clipboard operation
getbem.github.io copied to clipboard

Should nesting same name blocks be allowed?

Open Intregrisist opened this issue 7 years ago • 4 comments

So I was having a conversation with a colleague and I stated that we should not be nesting a BEM block within itself because it can cause CSS selector nightmare. Below I will show a simple example:

<div class="foo foo--blue">
  <div class="foo foo--red">
    <span class="foo__text">Hello World</span>
  </div>
</div>
.foo {
  .text {
    .foo--red & {
      color: red;
    }
    .foo--blue & {
      color: blue;
    }
  }
}

This is a very small and hopefully clear example. What color would .foo__text get? I can't find any guide that suggests or argues with nesting same named blocks.

Intregrisist avatar Feb 11 '17 00:02 Intregrisist

I think you are right, it causes unexpected and not desired complexity

iamstarkov avatar Feb 13 '17 19:02 iamstarkov

I think when you expect nesting like this you have to be more specific, using the > combinator:

.foo {
    &__text {
        .foo--red > & {
            color: red;
        }
        .foo--blue > & {
            color: blue;
        }
    }
}

jednano avatar Feb 17 '17 19:02 jednano

That can be a potential solution, but it enforces too much on the DOM hierarchy. This also makes it harder to manage the code when there are changes to the DOM. I think this can work on simple cases.

Intregrisist avatar Feb 17 '17 19:02 Intregrisist

When you're dealing with recursion, you really don't have a choice.

jednano avatar Feb 17 '17 19:02 jednano