:scope

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

: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 的作用域是带有 idcontext 的元素。所选元素是该上下文的直接子元素——element-1element-2——而不是它们的后代。

规范

规范
选择器 Level 4
# 作用域伪类

浏览器兼容性

另见