Simple dark/light mode toggle with Nuxt and Tailwind
Not sure what I am doing wrong, but I cannot manage for Tailwind to respect the "dark" class on my "html" element. It's set properly and my tailwind.config.js contains
darkMode: "class"
(tried other values too), but when I inspect my page tailwind still uses prefers-color-scheme selectors. I've also tried
to no avail.
ChatGPT and other AIs are also not able to create a minimal working project where an element with e.g. classes text-black dark:text-white
actually works. Any help is much appreciated!3 Replies
Hi @Jonas. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To implement a simple dark/light mode toggle in Nuxt with Tailwind CSS (using
UColorModeSwitch Component 4. CSS Example: CSS Variables and Dark Mode --- Summary:
If you use Nuxt UI or
darkMode: 'class'
), you should ensure the following:
1. Tailwind Config: Your tailwind.config.js
should have darkMode: 'class'
set.
2. Dark Class Placement: The dark
class should be applied to the <html>
or <body>
element, as Tailwind will look for this class to apply dark mode styles.
3. Nuxt Color Mode Integration: If you use Nuxt UI or the @nuxtjs/color-mode
module, it will handle toggling the dark
class for you and provide a composable to switch modes.
Example with Nuxt UI and Tailwind
1. Install Nuxt UI (which auto-installs @nuxtjs/color-mode):
2. Tailwind config:
3. Use the color mode composable to toggle:
This will toggle the dark
class on the <html>
element, and Tailwind will apply the correct styles. You do not need to manually manage the dark
class if you use Nuxt UI or @nuxtjs/color-mode
—they handle it for you automatically. If you want a ready-made toggle, you can use the <UColorModeSwitch />
component from Nuxt UI:
Nuxt UI Color Mode UsageUColorModeSwitch Component 4. CSS Example: CSS Variables and Dark Mode --- Summary:
If you use Nuxt UI or
@nuxtjs/color-mode
, and your Tailwind config is correct, toggling dark/light mode will work out of the box. The dark
class is managed for you, and Tailwind will respect it. If you are not using these modules, you must manually add/remove the dark
class on the <html>
element for Tailwind to apply dark styles.
If you still see prefers-color-scheme
selectors being used, double-check that you are not using darkMode: 'media'
anywhere, and that the dark
class is present on the <html>
or <body>
element when you expect dark mode to be active.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@170646731699126272> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Was my CSS file, thanks!