Stylus迁移Sass时父选择器拼接后缀生成类名的等效写法咨询
实现方案
你可以通过以下两种方式实现和Stylus ^[0] 完全等效的效果,编译输出和你给出的预期结果一致:
方案一:预定义外层类名变量(首选,兼容性最高、可读性最好)
// 先定义最外层类名变量 $root-class: '.service_list_item'; $accentColor: #e3c1c1; #{$root-class} { display: grid; position: relative; padding: 0 1.072rem; justify-items: center; &:hover { // 直接拼接后缀生成目标类 #{$root-class}_icon { background-color: $accentColor; } } }
方案二:使用Sass内置选择器函数(无需额外定义变量,适合动态嵌套场景)
需要Sass版本≥3.4,目前主流的Dart Sass完全支持:
$accentColor: #e3c1c1; .service_list_item { display: grid; position: relative; padding: 0 1.072rem; justify-items: center; &:hover { // 提取最顶层父选择器,拼接后缀 #{selector.nth(&, 1)}_icon { background-color: $accentColor; } } }
Sass中&指代当前上下文的父选择器链,selector.nth(&, 1)会提取选择器链中最顶层的.service_list_item,通过#{}插值语法即可完成后缀拼接。
内容的提问来源于stack exchange,提问作者DavichoDev
相关产品推荐
相关产品推荐

