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

在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


凤凰求蛊
浏览 154回答 2
2回答

MMTTMM

既然你的结构是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; }

慕工程0101907

实现你需要的效果,可以考虑下面的两种写法: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到时和&具有相同的机制,那么实现你要的功能就方便多了。
打开App,查看更多内容
随时随地看视频慕课网APP