`@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-rules 都會被保留。但如果您不希望這樣,您可以使用類似 媒體查詢特性 的語法,例如 @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-rules 的名稱之外,還有兩個特殊值可以用在 查詢中:

  • rule 指的是樣式規則。例如,@at-root (with: rule) 會排除所有 at-rules,但保留樣式 規則。

  • all 指的是所有 at-rules *和* 樣式規則都應該被 排除。