You need to enable JavaScript to run this app. SCSS/SASS存在两级父选择器时如何选择第二父级生成目标CSS
优惠活动
大模型
产品
解决方案
定价
更多

SCSS/SASS存在两级父选择器时如何选择第二父级生成目标CSS

问题原因

& 是SCSS的父选择器标识符,会直接返回当前层级以上的完整选择器字符串,你代码中内层的 & 取值为 html .ltr,直接和 span 拼接时没有空格分隔,就会得到错误的 spanhtml .ltr 选择器。

解决方案

可以使用SCSS内置的selector-replace选择器处理函数实现需求,无需拆分原有代码结构:

html {
    .ltr {
        direction: ltr;

        @at-root #{selector-replace(&, '.ltr', 'span.ltr')} {
            display: inline-block;
        }
    }
}

编译结果

html .ltr {
  direction: ltr;
}

html span.ltr {
  display: inline-block;
}

方案说明

  • selector-replace函数会匹配第一个参数传入的选择器中,和第二个参数匹配的部分,替换为第三个参数的内容,这里就是把html .ltr中的.ltr替换为span.ltr,自动保留外层的html选择器
  • @at-root规则保证生成的选择器会提升到样式根层级,不会嵌套在其他规则内

如果使用的SCSS版本较低不支持selector-replace,也可以用字符串替换的方式实现同等效果:

html {
    .ltr {
        direction: ltr;
        
        $full-parent-selector: #{"" + &};
        @at-root #{str-replace($full-parent-selector, '.ltr', 'span.ltr')} {
            display: inline-block;
        }
    }
}

内容的提问来源于stack exchange,提问作者Mehdi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 23:21:02