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 leaves your existing styles untouched. Mix in scoped <style> 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

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

Basic example.

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

Variables and child elements example.

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

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

```

πŸ”Ž Technical FAQ

🌘 Change Log

1.1.0