在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
是我对 & { } 选择理解有误,还是说我的写法有问题?
跟据 SCSS 官方的 Reference 来看,结果却是如此:
& will be replaced with the parent selector as it appears in the CSS. This means that if you have a deeply nested rule, the parent selector will be fully resolved before the & is replaced.
所以我们可以改写一下:
form { &.no-cssgradients { button { background: #333; } } button { background: linear-gradient(#444,#222); } }
实现你需要的效果,可以考虑下面的两种写法:
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
到时和&
具有相同的机制,那么实现你要的功能就方便多了。
既然你的结构是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; }
.