CSS :scope
Pseudo-Class
The :scope
pseudo-class in CSS represents the current element in the scope of a selector, typically the root of a component or a parent element in a query. It is especially useful when dynamically styling elements within a specific section of the DOM.
1. Syntax
Or within a specific container:
2. How :scope
Works
The :scope
pseudo-class targets the root element of a CSS selector scope, similar to :root
but applied within a particular section instead of the entire document.
🔹 By default, the :scope
pseudo-class refers to the parent element of a CSS selector inside a query (e.g., querySelector(':scope > div')
).
🔹 It is particularly useful in JavaScript-based styling when selecting elements dynamically.
3. Example – Styling the Scoped Element
✅ The <section>
gets a blue border and padding when inside .wrapper
.
4. Example – Using :scope
with Direct Children
✅ Only direct children <li>
inside .menu
get styled.
5. Example – JavaScript + :scope
document.querySelector(':scope > .highlight')
selects .highlight
only within the current scope.
✅ The :scope
selector ensures we only target .highlight
within that specific section
.
6. Browser Support
✅ Supported in Chrome, Edge, Firefox, and Safari.
❌ Not supported in Internet Explorer.
7. Best Practices
✔ Use :scope
for modular components.
✔ Works well with JavaScript for dynamic styling.
✔ Avoid using it for global styling—it’s best for scoped elements.