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:
- Create a new file
darkmode.js
in yourpublic
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);
- Update your
tailwind.config.js
file to include thedark
theme.
// tailwind.config.js
module.exports = {
theme: {
extend: {},
},
plugins: [],
variants: {
extend: {},
},
darkMode: 'class', // or 'media' or 'class'
};
- Update your
postcss.config.js
file to include thetailwind.config.js
file.
// postcss.config.js
module.exports = {
plugins: [require('tailwindcss')('./tailwind.config.js')],
};
- Add the
darkmode.js
file to yourindex.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>
-
Build your application for production using your build tool (e.g.,
npm run build
). This will generate the optimized production files, including thedarkmode.js
file. -
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.