CSS :scope Pseudo Classm

CSS :scope Pseudo Classm

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

:scope { property: value; }

Or within a specific container:

.container:scope { background-color: lightgray; }

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

<div class="wrapper"> <section> <p>Normal paragraph</p> <p class="highlight">Highlighted paragraph</p> </section> </div>
section:scope { border: 2px solid blue; padding: 10px; }

✅ The <section> gets a blue border and padding when inside .wrapper.

4. Example – Using :scope with Direct Children

<ul class="menu"> <li>Item 1</li> <li>Item 2</li> </ul>
.menu:scope > li { color: red; font-weight: bold; }

✅ Only direct children <li> inside .menu get styled.

5. Example – JavaScript + :scope

document.querySelector(':scope > .highlight') selects .highlight only within the current scope.

const section = document.querySelector('section'); const highlight = section.querySelector(':scope > .highlight'); highlight.style.color = 'blue';

✅ 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close