I am using BEM for the first time in my latest project, using SASS and I love it. A lot of refactoring going on, however. One thing that I have not solved is the following, very common situation:
I have a block with a modifier, let's say .block, and .block_wide. In .block_wide there are multiple elements that will get minor tweaks depending on what block they are in. For example .block__image has to get a 100% width when the block is .block_wide. How to write this, preferably in scss?
This is the HTML situation:
<div class="block">
<div class="block__image"></div>
</div>
<div class="block block_wide">
<div class="block__image" /></div>
</div>
These are some wrong answers I came up with:
.block {
&__image { width: 50%; }
// Block level modifier
&_wide {
&__image { // This does not work because it results in an entirely new class that is not used in the markup
width: 100%;
}
}
}
In the previous "solution" I'm trying to write it the way I would like it to work but obviously it doesn't.
The next solution works but it feels absolutely wrong:
.block {
&__image {
width: 50%;
.block_wide & {
width: 100%;
}
}
// Block level modifier
&_wide {} // Nothing here
}
Now there is no clarity in the source css at all and very quickly this will get out of hand. I'm probably trying to use BEM in a way that it's not meant to be used. If someone could enlighten me on the matter!
Another solution, a little more satisfying because it actually works. But I still want to know if this is BEM approved:
Hello,
Sorry for jumping in, in opinion BEM is mostly used as a naming convention, it shouldn't influence the way you write css while using a css pre-procesor, also SASS allows parent selectors, but that doesn't mean we have to use them everywhere. To me your html looks fine, and the scss could be simply written as:
or
or as you posted above.
Thanks, @adrianweb for commenting. This is a simple example, but in a big project you know how modifiers and media queries become very complex. I want to stay as close as possible to the BEM naming conventions so I can debug more easily, and results are predictable. Your solution is exactly what I am using now but I believe that as a rule of thumb, second level classes like .block_wide .block__image {} are to be avoided. Do you think this rule is still valid in this situation, or is this the proper way to do it?
Sure. It's totally allowed. Elements in blocks works like markers for some visual or functional mechanics. For modified blocks their elements can have modified mechanics as well. So it's totally valid.
Shouldn't it look like this:
I suggest using something more explicit to denote modifier, so as to block__image_[unique-modifier] would clearly point out correlation with block_[unique-modifier].