如何在SCSS中选择自身元素,而非完整编译的父选择器?
Ah, I see exactly what's going on here! The problem stems from how SCSS handles the & selector when you assign it to $self inside your mixin. When you're in the .land .tree context, & captures the full chain .land .tree—not just the .tree class. So when you reference #{$self}__fruit inside the &--yellow modifier, you're effectively telling SCSS to write .land .tree__fruit nested under .land .tree--yellow, which leads to that duplicated .land in your compiled CSS.
Here's a clean, reusable fix that keeps your mixin flexible (since you mentioned it's used elsewhere):
The Fixed SCSS Code
.land { @mixin colorSet { $self: &; // Grab only the immediate block selector (e.g., .tree from .land .tree) $block: nth($self, -1); &__fruit { background: red; } &--yellow { // Use just the block selector to target the fruit element #{$block}__fruit { background: yellow; } } } .tree { @include colorSet(); } }
What This Compiles To
You'll get exactly the CSS you're expecting:
.land .tree__fruit { background: red; } .land .tree--yellow .tree__fruit { background: yellow; }
Why This Works
nth($self, -1)extracts the last selector from the$selflist. When the mixin is included inside.land .tree, this gives us.tree—perfect for targeting the BEM element.- Inside the
&--yellowmodifier (which resolves to.land .tree--yellow), using#{$block}__fruitcreates the correct BEM structure: the modifier class on the block, targeting the block's element.
This approach keeps your mixin reusable across different contexts too—if you include it in another parent class (like .garden .bush), it'll automatically grab .bush as the block selector without any extra changes.
内容的提问来源于stack exchange,提问作者Mizok.H

