css-scope-inline

🌘 CSS Scope Inline

cover (Art by shahabalizadeh)

Why does this exist?

✨ Want to also scope your <script> tags? See our companion project Surreal

πŸ‘οΈ How does it look?

<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.

🌘 How does it work?

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.

🎁 Install

βœ‚οΈ 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>

πŸ€” Why consider this over Tailwind CSS?

Use whatever you’d like, but there’s a few advantages with this approach over Tailwind, Twind, UnoCSS:

⚑ Workflow Tips

πŸ‘οΈ CSS Scope Inline vs Tailwind CSS Showdowns

Basics

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>

CSS variables and child elements

At first glance, Tailwind Example 2 looks very promising! Exciting …but:

Home
Team
Profile
Settings
Log Out
Home
Team
Profile
Settings
Log Out
Home
Team
Profile
Settings
Log Out

```

πŸ”Ž Technical FAQ