:scope
:scope CSS 偽類表示元素是選擇器匹配的參考點或作用域。
css
/* Selects a scoped element */
:scope {
background-color: lime;
}
:scope 匹配哪個元素取決於它使用的上下文。
- 當在樣式表的根級別使用時,
:scope等同於:root,在常規 HTML 文件中,它匹配<html>元素。 - 當在
@scope塊中使用時,:scope匹配塊定義的作用域根。它提供了一種從@scope塊內部對作用域根應用樣式的方法。 - 當在 DOM API 呼叫中使用時——例如
querySelector()、querySelectorAll()、matches()或Element.closest()——:scope匹配呼叫該方法的元素。
語法
css
:scope {
/* ... */
}
示例
使用 :scope 作為 :root 的替代方案
此示例顯示,當在樣式表的根級別使用時,:scope 等同於 :root。在這種情況下,提供的 CSS 將 <html> 元素的背景顏色設定為橙色。
css
:scope {
background-color: orange;
}
在 @scope 塊中使用 :scope 為作用域根設定樣式
在此示例中,我們使用兩個獨立的 @scope 塊分別匹配帶有 .light-scheme 和 .dark-scheme 類的元素內部的連結。請注意 :scope 如何用於選擇和提供作用域根本身的樣式。在此示例中,作用域根是應用了這些類的 <div> 元素。
HTML
html
<div class="light-scheme">
<p>
MDN contains lots of information about
<a href="/en-US/docs/Web/HTML">HTML</a>,
<a href="/en-US/docs/Web/CSS">CSS</a>, and
<a href="/en-US/docs/Web/JavaScript">JavaScript</a>.
</p>
</div>
<div class="dark-scheme">
<p>
MDN contains lots of information about
<a href="/en-US/docs/Web/HTML">HTML</a>,
<a href="/en-US/docs/Web/CSS">CSS</a>, and
<a href="/en-US/docs/Web/JavaScript">JavaScript</a>.
</p>
</div>
CSS
css
@scope (.light-scheme) {
:scope {
background-color: plum;
}
a {
color: darkmagenta;
}
}
@scope (.dark-scheme) {
:scope {
background-color: darkmagenta;
color: antiquewhite;
}
a {
color: plum;
}
}
結果
在 JavaScript 中使用 :scope
此示例演示了在 JavaScript 中使用 :scope 偽類。如果您需要獲取已檢索到的 Element 的直接後代,這會很有用。
HTML
html
<div id="context">
<div id="element-1">
<div id="element-1.1"></div>
<div id="element-1.2"></div>
</div>
<div id="element-2">
<div id="element-2.1"></div>
</div>
</div>
<p>
Selected element ids :
<span id="results"></span>
</p>
JavaScript
js
const context = document.getElementById("context");
const selected = context.querySelectorAll(":scope > div");
document.getElementById("results").textContent = Array.prototype.map
.call(selected, (element) => `#${element.getAttribute("id")}`)
.join(", ");
結果
context 的作用域是帶有 id 為 context 的元素。所選元素是該上下文的直接子元素——element-1 和 element-2——而不是它們的後代。
規範
| 規範 |
|---|
| 選擇器 Level 4 # 作用域偽類 |
瀏覽器相容性
載入中…