CSS :scope

The :scope pseudo-class is a powerful selector that allows you to target the current element that is the context for any nested selectors. It is particularly useful when you want to style elements that are direct children of a specific parent or context, without introducing additional classes or IDs. This tutorial will teach you how to use :scope effectively with examples.

Understanding :scope

The :scope pseudo-class matches the element that is the current context for a scoped query. It is commonly used in conjunction with descendant selectors.

Example 1: Basic Usage of :scope

In this example, we'll style a list of fruits. The list items will be styled only if they are children of an unordered list that is scoped to a specific section.

<fieldset class="example">
  <legend>Result:</legend>
  <section class="fruit-section">
    <ul>
      <li>Apple</li>
      <li>Banana</li>
      <li>Cherry</li>
    </ul>
  </section>
</fieldset>

<style>
  .fruit-section > ul > li:scope {
    color: red;
  }
</style>
Result:
  • Apple
  • Banana
  • Cherry

Example 2: Nested Elements

Here we will use :scope to style list items in a specific way when they are direct children of a particular list.

<fieldset class="example">
  <legend>Result:</legend>
  <div class="container">
    <ul>
      <li>First Item</li>
      <li>Second Item</li>
      <li>Third Item</li>
    </ul>
  </div>
</fieldset>

<style>
  .container > ul > li:scope {
    font-weight: bold;
  }
</style>
Result:
  • First Item
  • Second Item
  • Third Item

Example 3: Combining with Other Selectors

In this last example, we will demonstrate how :scope works with other selectors, allowing for more complex styling rules.

<fieldset class="example">
  <legend>Result:</legend>
  <article class="post">
    <h2>Post Title</h2>
    <p>This is an example post.</p>
    <ul>
      <li>Comment 1</li>
      <li>Comment 2</li>
    </ul>
  </article>
</fieldset>

<style>
  .post:scope h2 {
    color: blue;
  }
  .post:scope ul > li:scope {
    color: green;
  }
</style>
Result:

Post Title

This is an example post.

  • Comment 1
  • Comment 2

Conclusion

The :scope pseudo-class can be a very useful tool in your CSS toolkit, especially when working with nested elements. By narrowing the context of your selectors, you can reduce specificity issues and keep your styles clean and maintainable.