reactjstailwind-cssvitepostcsstailwind-3

Dark Mode Toggle in Tailwind CSS not working in older browsers


I'm currently working on a project using Tailwind CSS for styling, and I've implemented a dark mode toggle feature. The toggle works perfectly in the latest version of Chrome but it doesn't work in older versions (e.g., Chrome 87 on Android).

When toggling to dark mode, the expected behavior is to apply dark mode classes like dark:bg-slate-900, but in older browsers, it keeps the light mode classes (e.g. bg-gray-50).

// tailwind.config.cjs
module.exports = {
  future: {
    hoverOnlyWhenSupported: true,
  },
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  darkMode: "class",
}

// Dark mode toggle logic
useEffect(() => {
  if (
    localStorage.getItem("theme") === "dark" ||
    localStorage.getItem("theme") === null
  ) {
    document.documentElement.style.backgroundColor = "#0f172a";
    document.documentElement.classList.add("dark");
  } else {
    document.documentElement.style.backgroundColor = "#fcfefc";
    document.documentElement.classList.remove("dark");
  }
}, [theme]);

// postcss.config.cjs
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

package.json file
{
  "name": "decker",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
...
  },
  "devDependencies": {
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.31",
    "tailwindcss": "^3.3.4",
    "typescript": "^5.1.3",
    "vite": "5.0.12",
    "vite-plugin-pwa": "^0.17.4"
  }
}

How do I make dark and light mode work in older browsers as well?


Solution

  • With Tailwind v3.3+, the selectors of CSS rules for dark: variant classes with darkMode: 'class' are generated with the :is() pseudo class. Can I use… reports this was supported in Chrome for Android starting from version 121 and MDN reports Chrome for Android support starting from version 88. Either way, this :is() usage would be why dark: variant classes have no effect on Chrome for Android version 87.

    To work around this compatibility you could consider: