<html> <head> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-for-dark-mode.png" media="(prefers-color-scheme: dark)" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-for-light-mode.png" media="(prefers-color-scheme: light)" /> </head> <body> My awesome website ✨ </body> </html>
Change favicon based on dark/light color mode
Introduction
In the past, most of the Operating Systems had only light color mode. But, it was hurting our eyes when we use our mobile/desktop screens for longer period of time.
To resolve that issue, nowadays many Operating Systems have support to change color mode to dark.
Problem
When we use dark color mode, all the native application windows also changes its color to dark. This cause issue that favicon designed for light color mode no longer getting visible properly on dark color mode as shown in below image.
Solutions
There are two solutions for this problem.
1. Using media attribute of link element
For this solution, we need to create two favicon image files. One for light color mode and another for dark color mode.
Once we have two favicon image files, we can serve different favicon by setting prefers-color-scheme
media query in media
attribute of <link>
element as shown below:
After implementing above code, we can see that favicon gets changed on change of light/dark color mode in our Operating System.
This solution works in all the modern browsers and devices.
2. Using SVG favicon
For this solution we need only one favicon image but in SVG file format.
In that SVG file, We need to add prefers-color-scheme
media query to change fill/stroke colors of the SVG image based on dark/light color mode.
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"> <style> // set fill/stroke colors of favicon for light color mode here @media (prefers-color-scheme: dark) { // change fill/stroke colors of favicon for dark color mode here } </style> <!-- SVG image code here --> </svg>
Unfortunately as of writing this tip, SVG favicon is not supported in all modern browsers. So, it is safer to go with 1st solution for now and in future when it is supported by all modern browsers, go with this solution to have only one favicon image file.
Do you have any question related to this post? Just Ask Me on Twitter