@at-root
@at-root
规则通常写作 @at-root <选择器> { ... }
,它会使其中的所有内容直接输出到文档的根部,而不使用正常的嵌套。它最常用于使用 高级嵌套和 SassScript 父选择器以及选择器函数。
For example, suppose you want to write a selector that matches the outer
selector and an element selector. You could write a mixin like this one that
uses the selector.unify()
function to combine &
with a user’s selector.
SCSS Syntax
@use "sass:selector";
@mixin unify-parent($child) {
@at-root #{selector.unify(&, $child)} {
@content;
}
}
.wrapper .field {
@include unify-parent("input") {
/* ... */
}
@include unify-parent("select") {
/* ... */
}
}
Sass Syntax
@use "sass:selector"
@mixin unify-parent($child)
@at-root #{selector.unify(&, $child)}
@content
.wrapper .field
@include unify-parent("input")
/* ... */
@include unify-parent("select")
/* ... */
CSS Output
.wrapper input.field {
/* ... */
}
.wrapper select.field {
/* ... */
}
这里需要 @at-root
规则,因为在执行选择器嵌套时,Sass 不知道用什么插值生成了选择器。这意味着即使你使用 &
作为 SassScript 表达式,它也会自动将外部选择器添加到内部选择器中。@at-root
明确告诉 Sass 不要包含外部选择器(尽管在 &
作为表达式时总是会被包含)。
💡 Fun fact:
@at-root
规则还可以写作 @at-root { ... }
来将多个样式规则放在文档的根部。事实上,@at-root <选择器> { ... }
只是 @at-root { <选择器> { ... } }
的简写!
超越样式规则超越样式规则 permalink
单独使用 @at-root
只会去除样式规则。像 @media
或 @supports
这样的 at-rules 将保留。如果这不是你想要的,你可以使用类似媒体查询特性的语法来精确控制包含或排除的内容,写作 @at-root (with: <规则...>) { ... }
或 @at-root (without: <规则...>) { ... }
。(without: ...)
查询告诉 Sass 应该排除哪些规则;(with: ...)
查询排除所有除了列出的规则之外的规则。
SCSS Syntax
@media print {
.page {
width: 8in;
@at-root (without: media) {
color: #111;
}
@at-root (with: rule) {
font-size: 1.2em;
}
}
}
Sass Syntax
@media print
.page
width: 8in
@at-root (without: media)
color: #111
@at-root (with: rule)
font-size: 1.2em
CSS Output
@media print {
.page {
width: 8in;
}
}
.page {
color: #111;
}
.page {
font-size: 1.2em;
}
除了 at-rules 的名称外,还有两个特殊值可以在查询中使用:
-
rule
指样式规则。例如,@at-root (with: rule)
排除所有 at-rules,但保留样式规则。 -
all
指所有 at-rules 和 样式规则都应被排除。