Is it possible to use a different favicon for browsers that support theme-color?

richardwestenra picture richardwestenra · Apr 20, 2018 · Viewed 6.9k times · Source

Is there a way to set a different favicon for browsers that support theme-color, either via the meta tag or manifest.json? I have a jet black theme bar, but a mostly-black favicon for use on desktop browsers. I'd like to have an alternate white favicon for mobile browsers, but I don't want to make the assumption that mobile browser === theme-color support, as that's not always going to be the case.

Desktop favicon example:

Desktop favicon

Mobile favicon example: Mobile favicon

Answer

philippe_b picture philippe_b · Apr 21, 2018

The browser's theme is accessible through the prefers-color-scheme media query. Unfortunately, as the favicon is not a page element, you cannot use the media query in a CSS file to, say, switch between two images.

The solution is to combine prefers-color-scheme with SVG, which can embed CSS. Declare an SVG favicon:

<link rel="icon" href="my_icon.svg">

And use the media query in the SVG itself:

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <style>
    circle {
      fill: yellow;
      stroke: black;
      stroke-width: 3px;
    }
    @media (prefers-color-scheme: dark) {
      circle {
        fill: black;
        stroke: yellow;
      }
    }
  </style>
  <circle cx="50" cy="50" r="47"/>
</svg>

Source at tomoyac.com

SVG favicon is still an advanced feature. It is already supported by Firefox and by Chrome, but other browsers do not support it yet.