System Dark/Light mode favicon

Viewed 128

[solved] I am trying to make a dark/light mode icon for my website, so I made the code:

<svg>
 <style>
    @media (prefers-color-scheme: dark) {
      .dark {
        display:none;
      }
      .light {
        display:true;
      }
    }
    @media (prefers-color-scheme: light) {
      .dark {
        display:true;
      }
      .light {
        display:none;
      }
    }
  </style>
<img x="0" y="0" class="dark" src="https://7c-code.tk/favicon/icon-dark.png" width="100px" height="100px" ></img>
<img x="0" y="0" class="light" src="https://7c-code.tk/favicon/icon-dark.png" width="100px" height="100px" ></img>
</svg>

It works correctly, but it can only render in html, so I changed it into

<svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg">
 <style>
    @media (prefers-color-scheme: dark) {
      .dark {
        display:none;
      }
      .light {
        display:true;
      }
    }
    @media (prefers-color-scheme: light) {
      .dark {
        display:true;
      }
      .light {
        display:none;
      }
    }
  </style>
<img x="0" y="0" class="dark" src="https://7c-code.tk/favicon/icon-dark.png" width="100px" height="100px" ></img>
<img x="0" y="0" class="light" src="https://7c-code.tk/favicon/icon-dark.png" width="100px" height="100px" ></img>
</svg>

Now all the elements are positioned to the bottom right for some reason, even though I specified an x and y position for the images. How do I fix this? Thanks in advance!

Edit: Turns out I was just being dumb, I did not know that html img was different from svg image. Solved it, here is my code now:

<svg viewbox="0 0 100 100"  xmlns="http://www.w3.org/2000/svg">
 <style>
    @media (prefers-color-scheme: dark) {
      .dark {
        display:none;
      }
      .light {
        display:true;
      }
    }
    @media (prefers-color-scheme: light) {
      .dark {
        display:true;
      }
      .light {
        display:none;
      }
    }
  </style>
<image x="0" y="0" class="dark" href="https://7c-code.tk/favicon/icon-dark.png" width="100px" height="100px" ></image>
<image x="0" y="0" class="light" href="https://7c-code.tk/favicon/icon-dark.png" width="100px" height="100px" ></image>
</svg>
1 Answers

This is just a guess, but you might be dealing with viewbox issues. If I'm not mistaken, the x= and y= (viewbox attributes) must go on the SVG tag not on the <image> tag within the SVG.

Also, you may have misspelled the SVG <image> tag

See this other answer for details re the viewbox:

How to use the <svg> viewBox attribute?

Related