(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 method also leaves your existing styles untouched, allowing you to mix and match 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]
on each style).<div>
. Use a local <style>
per group..css
files. Just replace me
@media
queries for responsive design.
sm
md
lg
xl
xx
πxs-
sm-
md-
lg-
xl-
π’ None (xx)xx
not 2xl
to not break CSS highlighters.div[n1]
for <div n1>
instead of div:nth-child(1)
Tailwind verbosity goes up with more child elements.
<!-- 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! Exciting β¦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.