CodexBloom - Programming Q&A Platform

CSS Variables implementation guide Dynamically on Theme Switch with Tailwind CSS

πŸ‘€ Views: 75 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-07
css tailwind-css themes JavaScript

I'm working on a personal project and I'm having trouble getting CSS variables to update dynamically when switching themes in my Tailwind CSS project... I'm using Tailwind CSS version 3.0 and I set up my themes to change primary colors using CSS variables like so: ```css :root { --primary-color: #1d4ed8; } [data-theme='dark'] { --primary-color: #3b82f6; } ``` In my HTML, I have a button that toggles a 'dark' attribute on the `<html>` element: ```html <button id="theme-toggle">Toggle Theme</button> ``` Here's the JavaScript I'm using to handle the theme switch: ```javascript document.getElementById('theme-toggle').addEventListener('click', function() { document.documentElement.toggleAttribute('data-theme', 'dark'); }); ``` The question is that when I click the button to switch themes, the background of my components doesn't change as expected. I tried applying the primary color using the variable in my Tailwind classes like this: ```html <div class="bg-[var(--primary-color)] h-64 w-full"> Theme Test </div> ``` However, it seems like the styles don’t update until I refresh the page. I checked the console for any errors, but there doesn’t seem to be any indication of what's going wrong. I'm not using any additional JavaScript frameworks, just plain JavaScript. Could this be a caching scenario with Tailwind CSS, or am I missing something with the CSS variable setup? Any insights would be appreciated! I'm working on a application that needs to handle this. Is there a better approach?