Creating SVG that appears black in light mode and light in dark mode

Viewed 6921

I have a logo that will need to appear in the header and footer of a website I am working on, and the site has an option to toggle between light and dark mode. I need the black elements of the logo to appear black when the dark mode is on, and light when the light mode is on. I have tried the following CSS:

svg { fill:="currentColor"}

but for some reason that causes the black elements to disappear entirely instead of setting them to the default color. How can I make this work? The only other potential solution I am aware of is to convert the svg to a font and then imbed that in the site, but I would like to avoid doing that if it all possible.

3 Answers

You can add CSS to your SVG directly. For example, here's one that directly using the browsers light / dark settings

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
   <style>
        path {
            fill: black;
        }
        @media (prefers-color-scheme: dark) {
            path { fill: white; }
        }
    </style>
    <path d="..."/>
</svg>

WARNING: the following part of my answer is untested and might not work for an .svg source in an <img> tag, or even for an <svg> tag. If someone tests it, please comment below so I can edit my answer and not provide misleading information.

If you are using something else to "trigger" the dark theme, you can just change the media query to whatever else you need, like a global class:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
   <style>
        path {
            fill: black;
        }
        body.dark-theme path {
            fill: white;
        }
    </style>
    <path d="..."/>
</svg>

You can simply do it with a CSS class just add a CSS class to the body when dark mode is on let's say darkMode then set fill colors based on it

function myFunction() {
      document.querySelector("#body").classList.toggle('darkMode');
}
.darkMode{
background:black;
height:100vh;
}
svg{ fill:black;}
.darkMode svg {fill:white;}
<div id="body">
<svg height="100" width="100">
  <circle cx="50" cy="50" r="40"/>
</svg> 
<br>
<button onclick="myFunction()">Toggel</button>
</div>

Try to change your css to the following:

svg { fill=currentColor }

It is possible that your icons are appearing to disappear because they are black on a black background. Also check if they are implemented using stroke rather than fill - post your svg to answer that.

Also note that there is a built-in prefers-color-scheme css media query that allows this. More information in the links below.

References:

Related