GitHub - gnat/css-scope-inline: 🌘 Scope your inline style tags in pure vanilla CSS! Only 16 lines. No build. No dependencies. (original) (raw)

🌘 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?

I'm blue

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.

red
green
green
green
yellow
blue
green
green
red
green
green
green
yellow
blue
green
green

CSS variables and child elements

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

Home
Team
Profile
Settings
Log Out
    <!-- Tailwind Example 1 -->
    <div class="mx-2 my-4">
        <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Home</a></div>
        <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Team</a></div>
        <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Profile</a></div>
        <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Settings</a></div>
        <div><a href="#" class="block py-2 px-3 my-2 bg-[--color-1] rounded-lg text-center hover:bg-[--color-1-active] hover:text-white">Log Out</a></div>
    </div>

    <!-- Tailwind Example 2 -->
    <div class="mx-2 my-4
        [&_div_a]:block [&_div_a]:py-2 [&_div_a]:px-3 [&_div_a]:my-2 [&_div_a]:bg-[--color-1] [&_div_a]:rounded-lg [&_div_a]:text-center
        [&_div_a:hover]:bg-[--color-1-active] [&_div_a:hover]:text-white">
        <div><a href="#">Home</a></div>
        <div><a href="#">Team</a></div>
        <div><a href="#">Profile</a></div>
        <div><a href="#">Settings</a></div>
        <div><a href="#">Log Out</a></div>
    </div>
</body>

🔎 Technical FAQ