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>
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>
Key advantages include:
While parent class prepending offers similar scoping (.media
, .media img
, .media .content
), CSS nesting provides a more concise alternative:
<code>.media { & img { } & .content { } }</code>
However, @scope
offers unique capabilities. "Donut scoping" allows precise control over scope boundaries:
<code>@scope (.media) to (.content) { p { } }</code>
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>
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!