Can I somehow refactor the following code snippet to get rid of double modifier declaration?
.block {
&__element {
rule: value;
}
&--modifier {
rule: value;
}
&--modifier & {
&__element {
rule: value;
}
}
}
Output wanted:
.block {
property: value;
}
.block--modifier {
property: value;
}
.block--modifier .block__element {
property: value;
}
Nesting elements inside modifiers is a known issue. There are a lot of workarounds.
And use it interpolated when creating a element inside a modifier.
.block {
$block: &;
&__element {
property: value;
}
&--modifier {
property: value;
#{$block}__element {
property: value;
}
}
}
See output below.
It'll get the parent selector and cut the word before --
(which is the block). Looks hacky, but it's the simplest way to go.
@function block() {
$selector: str-slice(inspect(&), 2, -2);
$index: str-index($selector, '--') - 1;
@return str-slice($selector, 0, $index);
}
Which will return the name of the block so you don't have to repeat it.
.block {
property: value;
&--modifier {
property: value;
#{block()}__element {
property: value;
}
}
}
See output below.
.block {
property: value;
}
.block--modifier {
property: value;
}
.block--modifier .block__element {
property: value;
}
You can place the block within the &--modifier
selector like this, using the class name of the block rather than &
to target it.
.block {
&__element {
rule: value;
}
&--modifier {
rule: value;
.block {
&__element {
rule: value;
}
}
}
}
However, this is possibly not the best BEM solution, you should consider renaming the nested block as an element of the containing block, such as .block__another-element
or creating a new block entirely.
You could add &
alongside the modifier for a solution similar to Toni's.
.block {
&__element {
rule: value;
}
&--modifier & {
rule: value;
&__element {
rule: value;
}
}
}
This would however require .block
to be a root selector and not nested inside any other selector.
Just another possible solution. For most situations though, I would still prefer Toni's solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With