You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SCSS中选择自身元素,而非完整编译的父选择器?

Fixing Duplicate Selector Issue in SCSS BEM Mixin

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 $self list. When the mixin is included inside .land .tree, this gives us .tree—perfect for targeting the BEM element.
  • Inside the &--yellow modifier (which resolves to .land .tree--yellow), using #{$block}__fruit creates 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:04:46