getbem.github.io
getbem.github.io copied to clipboard
Should nesting same name blocks be allowed?
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.
I think you are right, it causes unexpected and not desired complexity
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;
}
}
}
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.
When you're dealing with recursion, you really don't have a choice.