Chrome is still implementing (prefers-color-scheme: dark)
, so the jury’s still out. https://crbug.com/889087. In Chrome 76 with --enable-blink-features=MediaQueryPrefersColorScheme
, this correctly sets the icon when the page is loaded, but does not respond dynamically to changes in dark mode.
Safari adds a grey background to dark icons in dark mode (for example, Wikimedia Foundation, Github), so this workaround isn't necessary for legibility.
-
Add two
link rel=icon
elements withid
s for later:<link rel="icon" href="a.png" id="light-scheme-icon"> <link rel="icon" href="b.png" id="dark-scheme-icon">
-
Create a CSS media matcher:
matcher = window.matchMedia('(prefers-color-scheme: dark)'); matcher.addListener(onUpdate); onUpdate();
-
Add/remove the elements from the document's
head
:lightSchemeIcon = document.querySelector('link#light-scheme-icon'); darkSchemeIcon = document.querySelector('link#dark-scheme-icon'); function onUpdate() { if (matcher.matches) { lightSchemeIcon.remove(); document.head.append(darkSchemeIcon); } else { document.head.append(lightSchemeIcon); darkSchemeIcon.remove(); } }
sasa