Change Favicon Based on Color Scheme
Here's how to change an SVG favicon.svg based on the user's color scheme preference.
Set the favicon
First, create an SVG favicon, then set it in the document's head
:
<head>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
</head>
A common path is the root. Just put it wherever you want to serve your static assets from and adjust the href
accordingly.
Adjust the svg
Now within the svg itself, you can put the styles for whether you'd like this displayed as a lighter color in dark mode (ie, dark background) or a darker color in light mode (ie, light background). For example:
<svg>
<style>
path {
fill: rgb(150,75,46);
}
@media (prefers-color-scheme: dark) {
path {
fill: rgb(249,142,44);
}
}
</style>
<path d="..." />
</svg>
The actual style may vary based on the construction of your svg. In this example, we are adjusting all paths which are fill
s. Yours may be stroke
s. Or you may have multiple paths, which could be fun.
Now, when you change your system color scheme between light and dark, you'll see the color of the favicon in the tab of your browser change to have the right kind of contrast.