Tailwindcss dark mode can't change <html> or add class="dark" tag on production. How to implement dark mode in Tailwindcss in production?

Updated: Feb 09, 2025

Tailwindcss dark mode can't change <html> or add class="dark" tag on production. How to implement dark mode in Tailwindcss in production?

To implement dark mode in Tailwind CSS in production, you cannot directly modify the HTML tag or add a class="dark" tag to the <html> tag due to security reasons. Instead, you can use JavaScript to toggle the dark mode class on specific elements or the <body> tag. Here's a step-by-step guide to implementing dark mode in Tailwind CSS in production:

  1. Create a new file darkmode.js in your public directory. This file will contain the JavaScript code to toggle the dark mode class.
// darkmode.js
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

const toggleDarkMode = () => {
  if (prefersDarkMode) {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
};

toggleDarkMode();

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', toggleDarkMode);
  1. Update your tailwind.config.js file to include the dark theme.
// tailwind.config.js
module.exports = {
  theme: {
    extend: {},
  },
  plugins: [],
  variants: {
    extend: {},
  },
  darkMode: 'class', // or 'media' or 'class'
};
  1. Update your postcss.config.js file to include the tailwind.config.js file.
// postcss.config.js
module.exports = {
  plugins: [require('tailwindcss')('./tailwind.config.js')],
};
  1. Add the darkmode.js file to your index.html file.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- head content -->
  </head>
  <body class="font-sans antialiased">
    <!-- body content -->
    <script src="/darkmode.js"></script>
  </body>
</html>
  1. Build your application for production using your build tool (e.g., npm run build). This will generate the optimized production files, including the darkmode.js file.

  2. Deploy your application to your production server.

Now, your Tailwind CSS dark mode will be functional in production without modifying the <html> tag directly. The JavaScript code in darkmode.js will handle the dark mode toggling based on the user's preference.