🎨 Polyfill for the legacy scoped
attribute on <style>
@scope
selector with more browsers likely to come—you should use this instead
📜 Use old-but-working proposal until @scope
gets here
💻 Works in all browsers
🥇 Uses fast regex to parse CSS selectors
:scope
⚖️ 4kb minzipped
This polyfill is based on the scoped
attribute as defined by the HTML spec in
early 2016. This section of the spec has since been removed. You can still view
it on archive.org though! It's successor is likely to be the @scope
at-rule. Use at your own risk.
🪀 Want to try it right now with no setup? Try it on CodeSandbox!
The best way to install this package on your website is to use a CDN. We provide a global classic non-module build that can be loaded directly from unpkg.com. You can also download and bundle it locally using npm if you want.
<script src="https://unpkg.com/style-scoped/scoped.min.js"></script>
npm install style-scoped
👷♂️ In the future we may provide an ESM bundle instead that can be used with modern JavaScript features. For now, though, we only offer a UMD build.
This polyfill supports all modern browsers. It requires WeakMap
and
MutationObserver
support.
After loading the polyfill, you can use the scoped
attribute on <style>
to
restrict the scope of the CSS rules to the parent element of the <style>
tag.
<div>Hello <span>world!</span></div>
<div>
<style scoped>
div:scope {
color: red;
}
span {
color: green;
}
</style>
Bonjour <span>monde!</span>
</div>
<div>¡Hola <span>Mundo!</span></div>
You can also use the :scope
pseudo-class to select the parent element of the
<style>
tag. This lets you do things that you can't do with an inline style
attribute. For example, you can use :hover
on the parent element:
<a href="https://example.org/">
<style scoped>
:scope:hover {
color: red;
}
</style>
Go to example.org
</a>
:scope
inside another selector (e.g. :is(div:scope)
) are
not currently supported and will be cleared. If this is actually something you
need, I will eat my hat. 🎩
TODO: Explain how it works
- The polyfill doesn't operate on all CSS rules.
@keyframes
,@font
, etc. are ignored. - If you depend on cross-domain CSS via
@import
, this is loaded dynamically with an XHR. It may take a little while to arrive. (📚 #2 & #3)
This project uses a devcontainer to provide a consistent development environment for contributors. You can use it with GitHub Codespaces online, or VS Code locally.
There are a few scripts you can run:
npm pack
: Build the project using Vitenpm test
: Run the tests using Vitest
🚀 These tasks are also available as VS Code Tasks.