Skip to content

Instantly share code, notes, and snippets.

@danielstgt
Last active August 15, 2024 15:47
Show Gist options
  • Save danielstgt/3981078dab453c77d817a0311056daa6 to your computer and use it in GitHub Desktop.
Save danielstgt/3981078dab453c77d817a0311056daa6 to your computer and use it in GitHub Desktop.
Tailwind CSS JavaScript Modifier/Variant

Usage

Use a js or no-js variant depending on the availability of JavaScript, e.g. no-js:hidden or js:bg-blue-500.

Tailwind CSS Config

const plugin = require('tailwindcss/plugin');

module.exports = {
    // ...

    plugins: [
        plugin(function({ addVariant, e }) {
            addVariant('no-js', ({ modifySelectors, separator }) => {
                modifySelectors(({ className }) => {
                    return `.no-js .${e(`no-js${separator}${className}`)}`;
                });
            });
        }),

        plugin(function({ addVariant, e }) {
            addVariant('js', ({ modifySelectors, separator }) => {
                modifySelectors(({ className }) => {
                    return `.js .${e(`js${separator}${className}`)}`;
                });
            });
        }),
    ],
}

index.html

<html class="no-js">
    <head>
        <script>document.documentElement.className=document.documentElement.className.replace('no-js','js')</script>
    </head>
    <body>
    </body>
</html>
@danielstgt
Copy link
Author

@PolMrt thanks for pointing that typo out, I've updated the gist 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment