Skip to content

Instantly share code, notes, and snippets.

@danielstgt
Last active November 29, 2021 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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('si-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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment