How to display a different favicon in dark or light mode

If you have a Mac set up to automatically switch between dark and light mode, you may have encountered the issue of having a white favicon that becomes almost invisible in light mode. Let’s explore how we can add a favicon in dark mode and a different one in light mode.

Unfortunately, there isn’t a straightforward way to achieve this for PNG/JPG bitmap images. However, we can use an SVG (Scalable Vector Graphics) trick to accomplish our goal. By embedding CSS within an SVG image, we can modify the color in dark mode, allowing us to have different colors for the two modes.

Here’s an example of an SVG file that can be used as a 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>

As you can see, the SVG image is simple and displays a half moon. The fill color of the path is set to #ccc in light mode and #fff in dark mode. This differentiation in color allows the favicon to be visible in both modes.

After saving the SVG file, you can use it as the favicon in your Gatsby website or any other appropriate platform.

Tags: dark mode, light mode, favicon, SVG