Sass中使用@content指令将主题类与父选择器合并为类组合选择器的实现问题
解决Sass Mixin中主题类与父选择器的并列/后代选择器切换问题
你目前的代码里,条件分支的逻辑没有区分两种使用场景,而且默认的选择器写法是后代关系,所以才会输出.Light .fixed这种结构。要实现主题类和父选择器的并列类效果,只需要调整&的拼接方式,并完善mixin的条件逻辑即可。
修正后的完整代码
$themes: ( Light: ( page_background: #ffffff, ), Dark: ( page_background: #181818, ) ); @function get_color($key) { @return map-get($theme-map, $key); } @mixin theme($makeAncestor: true) { @each $theme, $map in $themes { $theme-map: $map !global; @if $makeAncestor { // 场景1:主题类作为祖先元素(生成后代选择器) .#{$theme} & { @content; } } @else { // 场景2:主题类与父选择器属于同一元素(生成并列类选择器) .#{$theme}#{&} { @content; } } } $theme-map: null !global; } // 调用方式1:默认的祖先场景(输出 .Light .fixed-ancestor 这类后代选择器) .fixed-ancestor { @include theme() { background: get_color(page_background); } } // 调用方式2:并列类场景(输出 .Light.fixed 这类同一元素的多类选择器) .fixed { @include theme($makeAncestor: false) { background: get_color(page_background); } }
编译后的CSS结果
.Light .fixed-ancestor { background: #ffffff; } .Dark .fixed-ancestor { background: #181818; } .Light.fixed { background: #ffffff; } .Dark.fixed { background: #181818; }
核心逻辑说明
- Sass里的
&代表当前父选择器的完整字符串,比如在.fixed内部使用时,它会被替换成.fixed。 - 带空格的写法
.#{$theme} &会生成后代选择器,对应主题类元素下的父选择器元素。 - 无空格的拼接
.#{$theme}#{&}会把两个类合并到同一个元素上,形成你想要的并列类选择器。
内容的提问来源于stack exchange,提问作者stwhite
相关产品推荐
相关产品推荐

