Issue with prefers-color-scheme media query

I am trying to use svg favicon

<link rel="icon" type="image/svg+xml" href="/favicon.svg">

and I want to toggle favicon in dark mode browser so my code in svg file looks like

circle {
      fill: red;
      stroke: yellow;
    }
@media (prefers-color-scheme: dark) {
  circle  {fill: yellow;
        stroke: red; }
  }

But when I change my browser to dark mode favicon doesn’t toggle.

Can anyone help me with this?

Chrome version : Version 89.0.4389.90
Firefox version: 87.0 (64-bit)
Ubuntu: 16.04

Browsers, specially chrome cache favicon aggressively.

Try with a different browser and incognito mode after your first visit.

Failing that you might have to inline your svg CSS, sometimes it would ignore the CSS completely.

For clearing the cache I tried to reload the page with Empty Cache and Hard Reload in chrome. It still ignores dark theme codes.

as I said it can ignore the CSS most of the time, I think once the SVG is rendered, it won’t update like other HTML elements. I might be wrong.

I had inlined SVG definitions in my CSS. one for default one for dark mode so I could use a light bulb and crescent moon for them as well as having some nice animation if I wanted.

This simple vanilla JS to store, switch, load them

var btn = document.getElementById("btn-toggle");
    btn.addEventListener("click", function () {
        localStorage.theme === 'dark' ? white() : dark()
    })
    function dark() {
        localStorage.theme = 'dark';
        document.body.classList.add('dark-mode');
        btn.classList.add('dark');
    }
    function white() {
        localStorage.theme = 'white';
        document.body.classList.remove('dark-mode');
        btn.classList.remove('dark');
    }
    function theme() {
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            dark();
        } else {
            white();
        }
    }
    theme();
1 Like