Home > Web Front-end > CSS Tutorial > Early Days for CSS Scoping

Early Days for CSS Scoping

Joseph Gordon-Levitt
Release: 2025-03-20 10:11:10
Original
282 people have browsed it

Early Days for CSS Scoping

CSS scoping is gaining traction, with a current working draft specification representing significant progress. This proposal, spearheaded by Miriam Suzanne, addresses limitations of previous attempts.

The core concept centers around creating styles explicitly targeted at specific HTML components. The @scope rule facilitates this:

<code><div>
  <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Early Days for CSS Scoping "><div>
    <p>...</p>
  </div>
</div></code>
Copy after login

Styling this "component" becomes highly focused:

<code>@scope (.media) {
  :scope {
    display: grid;
    grid-template-columns: 50px 1fr;
  }
  img {
    filter: grayscale(100%);
    border-radius: 50%;
  }
  .content { ... }
}</code>
Copy after login

Key advantages include:

  1. Clear component-level styling, simplifying maintenance.
  2. Avoids naming conflicts; styles are contained within the component.

While parent class prepending offers similar scoping (.media, .media img, .media .content), CSS nesting provides a more concise alternative:

<code>.media {
  & img {
  }
  & .content {
  }
}</code>
Copy after login

However, @scope offers unique capabilities. "Donut scoping" allows precise control over scope boundaries:

<code>@scope (.media) to (.content) {
  p { }
}</code>
Copy after login

This prevents style leakage beyond the desired area:

<code><div>
  <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Early Days for CSS Scoping "><p>This is stylable in scope.</p>
  <div>
    <p>This is NOT styleable in scope.</p>
  </div>
</div></code>
Copy after login

The spec also elegantly handles "nearest ancestor" scenarios, a significant improvement over existing methods. Miriam's blog provides detailed explanations of this and other complexities, including overlapping scopes and interactions with nesting. Further exploration of her work is highly recommended.

The above is the detailed content of Early Days for CSS Scoping. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template