A TailwindCSS variant for class-based dark mode with Svelte's scoped stylesheets and CSS modules.

  • By Bryan Lee
  • Last update: Dec 1, 2022
  • Comments: 1

npm version npm downloads license build size

A TailwindCSS variant for class-based dark mode with Svelte's scoped stylesheets and CSS modules.

If you've ever tried to use TailwindCSS dark mode with Svelte and received an Unused CSS selector ".dark ..." error, this plugin is for you.

Motivations

TailwindCSS uses a global .dark class for its manual dark mode, and the dark: selector simply adds .dark as a parent selector. When the .dark selector gets scoped, it breaks manual dark mode functionality.

tailwindcss-global-dark introduces a gdark variant that adds the :global modifier to the .dark class used by TailwindCSS.

Usage

Simply replace dark: with gdark:

.incorrect { @apply dark:bg-red-400; /* transpiles to - .dark .incorrect {...} */ } .correct { @apply gdark:bg-green-400; /* transpiles to - :global(.dark) .correct {...} */ } ">
<style lang="postcss">
  .incorrect {
    @apply dark:bg-red-400;
    /* transpiles to - .dark .incorrect {...} */
  }

  .correct {
    @apply gdark:bg-green-400;
    /* transpiles to - :global(.dark) .correct {...} */
  }
style>

Installation

$ npm i tailwindcss-global-dark

Add the plugin to tailwind.config.cjs:

module.exports = {
  ...
  theme: { ... },
  plugins: [require('tailwindcss-global-dark')]
};

Github

https://github.com/bryanmylee/tailwindcss-global-dark

Comments(1)

  • 1

    Nice but it has a few issues

    Thanks for this great idea.

    I encountered issues with some classes and escaping though. For example the divide utilities were not working, I modified the code to this

    module.exports = plugin(({ addVariant, e}) => {
        addVariant('sv-dark', ({modifySelectors, separator}) => {
            modifySelectors(({ className }) => {
                return `:global(.dark) .${e(`sv-dark${separator}${className}`)}`
            })
        })
    })
    
    

    and things seem fine so far.