Changing the favicon in dark mode
By Flavio Copes
Learn how to show a different favicon in dark and light mode using an SVG favicon with embedded CSS and the prefers-color-scheme media query to swap colors.
To change your favicon in dark mode, use an SVG favicon with a <style> block inside it, and swap colors with the prefers-color-scheme media query. There’s no way to do this with PNG or JPG favicons, but SVG makes it work.
Here’s how I found this out. I have my Mac set up to automatically switch between dark and light mode.
I started building a new website when at some point I realized I put a white image as favicon, and in light mode it was almost invisible!
So I started investigating possible ways to add a favicon in dark mode and a different one in light mode.
Turns out there isn’t (yet) a way to do so for PNG/JPG bitmap images, but we can use an SVG vector images trick for this.
How the trick works
We can embed CSS in an SVG image. An SVG file is just XML, and it can contain a <style> tag, exactly like an HTML page.
That CSS supports media queries. When the browser renders the favicon, it evaluates prefers-color-scheme against the visitor’s system setting and applies the matching rules.
So if the image is simple enough that we can identify a color and change it in dark mode, we can have a different color for the 2 modes.
Here’s the SVG I used as favicon:
<svg
width="37"
height="45"
viewBox="0 0 37 45"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<style>
path {
fill: #ccc;
}
@media (prefers-color-scheme: dark) {
path {
fill: #fff;
}
}
</style>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M31.8831 2.04389C25.2462 2.72205 20 11.1737 20 21.5C20 32.2696 25.7062 41 32.7451 41C33.9877 41 35.2047 40.7279 36.3664 40.2206C32.5452 43.2149 27.7311 45 22.5 45C10.0736 45 0 34.9264 0 22.5C0 10.0736 10.0736 0 22.5 0C25.849 0 29.0271 0.731675 31.8831 2.04389Z"
/>
</svg>
The SVG image is very simple, it’s a half moon I designed in Figma and exported as SVG.
Then I filled the path color with the #ccc color in light mode, and #fff in dark mode. Light mode gets the gray moon, dark mode gets the white one.
I saved it as a .svg file and then used it as the favicon in Gatsby.
If you’re wiring it up by hand, this is the link tag:
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
Keep a PNG fallback
Here’s the catch: not every browser supports SVG favicons. Safari has lagged behind on this for years. Declare a PNG version too, and browsers that can’t use the SVG will pick it up:
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="icon" href="/favicon.png" type="image/png">
One more thing to be aware of: prefers-color-scheme follows the operating system setting, not your site’s own theme. If your site has a dark mode toggle, clicking it won’t change the favicon. The favicon only tracks what the OS (or browser) reports.
If you’re setting up favicons from scratch, my free favicon checklist lists all the files and link tags you need.