CodexBloom - Programming Q&A Platform

How to implement guide with css variable fallbacks optimization guide in safari for dark mode implementation

πŸ‘€ Views: 87 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
css safari dark-mode CSS

I've been researching this but I'm currently implementing a dark mode feature using CSS variables and am working with issues with Safari not respecting the fallbacks I've set for the variables. The idea is to have a variable for the text color that defaults to a light color when dark mode is not enabled. In Chrome and Firefox, this works seamlessly, but on Safari, the fallback color isn't applied, causing text to become nearly invisible. Here's a snippet of my CSS: ```css :root { --text-color: black; } [data-theme='dark'] { --text-color: white; } body { color: var(--text-color, gray); } ``` When I switch to dark mode using the `data-theme` attribute, it works as expected in Chrome. However, in Safari, if the user doesn't have dark mode enabled, the text color defaults to `gray`, which is only applied when the `--text-color` variable isn't defined. I've tried clearing the cache, and I've ensured that the `data-theme` is being correctly toggled in JavaScript. Here’s how I toggle the theme: ```javascript function toggleTheme() { const currentTheme = document.body.getAttribute('data-theme'); document.body.setAttribute('data-theme', currentTheme === 'dark' ? '' : 'dark'); } ``` Yet, I'm still working with the scenario where the fallback color is not being respected in Safari. Is there something unique about how Safari handles CSS variables or fallbacks that I might be overlooking? Any suggestions on how to make this work consistently across all browsers would be greatly appreciated. The stack includes Css and several other technologies. Is this even possible?