CSS Reference ยท Pseudo-classes
The :scope pseudo-class
Reference for the CSS :scope pseudo-class: the scoping root inside @scope rules, in querySelector calls, and as :root in ordinary stylesheets, with examples.
The :scope pseudo-class matches the scoping root, the element that a selector is anchored to. What that element is depends on the context:
- In an ordinary stylesheet it behaves like
:root. - Inside an
@scoperule it is the scope's root element. - In JavaScript calls such as
element.querySelectorAll(":scope > li")it is the element you called the method on.
@scope (.card) { :scope { border: 1px solid #cbd5e1; } }
Try it
The blue border comes from :scope, which here means each .panel. The paragraph inside .nested is cut off by the lower scope boundary and stays plain. This example needs a browser with @scope support.
Syntax
:scope { /* declarations */ }
list.querySelectorAll(":scope > li");
- Arguments: none.
- Specificity: (0, 1, 0).
Values
| Syntax and arguments | Description |
|---|---|
:scope in a stylesheet |
Matches the document root, like :root. |
:scope in @scope (.a) |
Matches the element selected by .a. |
:scope in el.querySelector() |
Matches el, so you can write selectors relative to it. |
Usage notes
- Direct children in JavaScript.
el.querySelectorAll("> li")is not valid, butel.querySelectorAll(":scope > li")returns only direct children. Without:scope, a selector like"div p"can match outsideel's own subtree structure. - Implicit use in
@scope. Inside an@scopeblock, a plain selector such aspis treated as:scope p. Write:scopeexplicitly to style the root itself. - Nested CSS. In a nested rule
&refers to the parent rule's selector, whereas:scoperefers to the scope root. They are not interchangeable. - No effect on specificity tricks. It is a normal pseudo-class, so it adds (0, 1, 0).
- Rarely needed in plain CSS. Outside
@scopethere is little reason to prefer it over:root.
Browser support
:scope has long worked in selector APIs and stylesheets in all browsers. The @scope at-rule that gives it a richer meaning is newer, so check support before relying on it for core layout.
Related
@scopeโ the at-rule that defines scoped styles:root:is()- Lesson: @scope
- Lesson: CSS Nesting