在嵌套 CSS 规则时,有时也需要直接使用嵌套外层的父选择器,例如,当给某个元素设定 hover
样式时,或者当 body
元素有某个 classname 时,可以用 &
代表嵌套规则外层的父选择器。
a {
font-weight: bold;
text-decoration: none;
&:hover { text-decoration: underline; }
body.firefox & { font-weight: normal; }
}
编译为
a {
font-weight: bold;
text-decoration: none; }
a:hover {
text-decoration: underline; }
body.firefox a {
font-weight: normal; }
编译后的 CSS 文件中 &
将被替换成嵌套外层的父选择器,如果含有多层嵌套,最外层的父选择器会一层一层向下传递:
#main {
color: black;
a {
font-weight: bold;
&:hover { color: red; }
}
}
编译为
#main {
color: black; }
#main a {
font-weight: bold; }
#main a:hover {
color: red; }
&
必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器,例如
#main {
color: black;
&-sidebar { border: 1px solid; }
}
编译为
#main {
color: black; }
#main-sidebar {
border: 1px solid; }
当父选择器含有不合适的后缀时,Sass 将会报错。