让ico跟随系统主题变化

353 阅读1分钟

🌓当我们切换亮/暗色主题是,页面中的ico并没有变化,如果我们想切换主题时,让ico一起变化,改怎么实现呢

借助别人的话
  • As of writing this, SVG favicons allowing inline media queries are supported in Firefox and Chromium based browsers.
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 447 428">\
<style>@media (prefers-color-scheme: dark) {
/* dark theme styles */
}
</style></svg>

一个属性,两个ico

<!-- icon.svg -->
<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>

当然,这只有在最新的浏览器中才可以看到

<!-- index.html -->
<link rel="icon" href="/icon.svg" />