Favicons that adapt to Dark Mode

Sometimes you might have a favicon with a transparent background that allows the tab colour to show through. The icon might have good contrast against the light tab colour when the user’s OS is in light mode, but become very hard to see for dark mode users.

icon is low contrast against dark tab

You could use a media query in your markup to serve different images, but if you’re using an SVG you can solve that directly in the image.

<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
:root {
    --color1: #616161;
    --color2: #4128da;
}

@media (prefers-color-scheme: dark) {
  :root {
    --color1: #eeeeee;
    --color2: #ff8723;
  }
}
</style>
<circle cx="63.5" cy="63.5" r="51.5" stroke="var(--color1)" stroke-width="8"/>
<rect x="43" y="44" width="41" height="9" fill="var(--color2)"/>
<rect x="43" y="72" width="41" height="9" fill="var(--color2)"/>
</svg>

By referencing CSS custom properties within the SVG code you can have the same image render with different colours.

Now you might find that even though the fav icon code is the same that some browsers cache the rendering of it and it doesn’t update at nightfall. If that’s a concern you might find re-applying the media queries in the markup is worthwhile.

Leave a Reply

Your email address will not be published. Required fields are marked *