(Art by shahabalizadeh)
this would work in <style> tags.@keyframes!@media queries were shorter for responsive design.β¨ Want to also scope your <script> tags? See our companion project Surreal
<div>
<style>
me { background: red; } /* β¨ this & self also work! */
me button { background: blue; } /* style child elements inline! */
</style>
<button>I'm blue</button>
</div>
See the Live Example! Then view source.
This uses MutationObserver to monitor the DOM, and the moment a <style> tag is seen, it scopes the styles to whatever the parent element is. No flashing or popping.
This leaves your existing styles untouched. Mix in scoped <style> at your leisure.
βοΈ copy + π paste the snippet into <script> in your <head>
Or, π₯ download into your project, and add <script src="script.js"></script> in your <head>
Or, π CDN: <script src="https://cdn.jsdelivr.net/gh/gnat/css-scope-inline@main/script.js"></script>
Use whatever youβd like, but thereβs a few advantages with this approach over Tailwind, Twind, UnoCSS:
[&>thing]).<div>. Use <style> on groups of elements.<style> and .css files. Just replace me1 rule = 1 line can be small like Tailwind. See examplesdiv[n1] for <div n1> (instead of div:nth-child(1))div>button@media queries for responsive design.
xx not 2xl to avoid breaking CSS highlighters.xs sm md lg xl xx π Endxs- sm- md- lg- xl- xx- π’ Default<!-- CSS Scope Inline -->
<div>
<style>
me { background: red; }
me div { background: green; }
me [n1] { background: yellow; }
me [n2] { background: blue; }
</style>
red
<div>green</div>
<div>green</div>
<div>green</div>
<div n1>yellow</div>
<div n2>blue</div>
<div>green</div>
<div>green</div>
</div>
<!-- Tailwind -->
<div class="bg-[red]">
red
<div class="bg-[green]">green</div>
<div class="bg-[green]">green</div>
<div class="bg-[green]">green</div>
<div class="bg-[yellow]">yellow</div>
<div class="bg-[blue]">blue</div>
<div class="bg-[green]">green</div>
<div class="bg-[green]">green</div>
</div>
At first glance, Tailwind Example 2 looks very promising, but:
```
querySelectorAll() and not just process the MutationObserver results directly?
<style>. This unfortunately involves re-scanning thousands of repeated elements. This is why querySelectorAll() ends up the performance (and simplicity) winner..me when used url() properties.