为了账号安全,请及时绑定邮箱和手机立即绑定

是我对 & { } 选择理解有误,还是说我的写法有问题?

是我对 & { } 选择理解有误,还是说我的写法有问题?

凤凰求蛊 2023-04-15 21:17:22
在SASS的介绍文档里,有下面这段代码:button {  background: linear-gradient(#444,#222);  .no-cssgradients & { background: #333 } }编译成CSS后是这样的:button {   background: linear-gradient(#444, #222); }/* 注意看下面这行 */.no-cssgradients button {  background: #333}但是,当有多个层级的选择器后,他将始终获得最顶层的选择器form {   button {    background: linear-gradient(#444,#222);    .no-cssgradients & { background: #333 }  // 问题在这行   } }如此,我期望编译后.no-cssgradients的顺序是这样的:form .no-cssgradients button但他的顺序却是这样的:.no-cssgradients form button
查看完整描述

2 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

既然你的结构是form>.no-css>button
为什么却在SCSS里用button包住.no-css呢?

form {  button { background: linear-gradient(#444,#222);  }  .no-css{ background: #333; 
    button {@extend .no-css}
  }
}

=====>

form button {  background: linear-gradient(#444444, #222222); }form .no-css, form .no-css button {  background: #333; }


查看完整回答
反对 回复 2023-04-18
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

实现你需要的效果,可以考虑下面的两种写法:

form {    button {        background: linear-gradient(#444,#222);
    }    @at-root #{&} .no-cssgradients  {        button {            background:#333;
        }
    }
}

或者:

form {    button {        background: linear-gradient(#444,#222);
    }    .no-cssgradients {        button {            background:#333;
        }
    }
}

这两种方法转译出来都是:

form button {  background: linear-gradient(#444444, #222222); }form .no-cssgradients button {  background: #333; }

假设置@at-root到时和&具有相同的机制,那么实现你要的功能就方便多了。


查看完整回答
反对 回复 2023-04-18
  • 2 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信