@at-root
@at-root 规则通常写成 @at-root <selector> { ... },它会导致其内部的所有内容在文档根目录处发出,而不是使用正常的嵌套。它最常用于使用 SassScript 父选择器和选择器函数进行高级嵌套。
例如,假设您想编写一个选择器来匹配外部选择器和元素选择器。您可以编写一个像这样的 Mixin,它使用 selector.unify() 函数来组合 & 和用户选择器。
SCSS 语法
@use "sass:selector";
@mixin unify-parent($child) {
@at-root #{selector.unify(&, $child)} {
@content;
}
}
.wrapper .field {
@include unify-parent("input") {
/* ... */
}
@include unify-parent("select") {
/* ... */
}
}
Sass 语法
@use "sass:selector"
@mixin unify-parent($child)
@at-root #{selector.unify(&, $child)}
@content
.wrapper .field
@include unify-parent("input")
/* ... */
@include unify-parent("select")
/* ... */
CSS 输出
.wrapper input.field {
/* ... */
}
.wrapper select.field {
/* ... */
}
这里需要 @at-root 规则,因为 Sass 在执行选择器嵌套时不知道用于生成选择器的插值。这意味着它会自动将外部选择器添加到内部选择器中,即使您使用 & 作为 SassScript 表达式。@at-root 明确地告诉 Sass 不要包含外部选择器。
💡 趣闻
@at-root 规则也可以写成 @at-root { ... },将多个样式规则放在文档根目录处。事实上,@at-root <selector> { ... } 只是 @at-root { <selector> { ... } } 的简写形式!
超越样式规则超越样式规则 链接
@at-root 本身只去除样式规则。任何像 @media 或 @supports 这样的 At-规则都会保留。但是,如果您不希望这样,可以使用类似于媒体查询功能的语法来控制它包含或排除的内容,写成 @at-root (with: <rules...>) { ... } 或 @at-root (without: <rules...>) { ... }。(without: ...) 查询告诉 Sass 哪些规则应该被排除;(with: ...) 查询排除所有规则,除了列出的那些规则。
SCSS 语法
@media print {
.page {
width: 8in;
@at-root (without: media) {
color: #111;
}
@at-root (with: rule) {
font-size: 1.2em;
}
}
}
Sass 语法
@media print
.page
width: 8in
@at-root (without: media)
color: #111
@at-root (with: rule)
font-size: 1.2em
CSS 输出
@media print {
.page {
width: 8in;
}
}
.page {
color: #111;
}
.page {
font-size: 1.2em;
}
除了 At-规则的名称,还有两个特殊值可以用于查询
-
rule指的是样式规则。例如,@at-root (with: rule)排除所有 At-规则,但保留样式规则。 -
all指的是所有 At-规则和样式规则都应该被排除。