Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

svg

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.

like image 969
user15641284 Avatar asked Aug 31 '25 02:08

user15641284


2 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>
like image 172
Sheraff Avatar answered Sep 02 '25 17:09

Sheraff


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:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#currentcolor_keyword
  • https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
  • Issue with embedded SVG images in dark mode
  • https://css-tricks.com/dark-mode-favicons/
  • https://web.dev/prefers-color-scheme/
  • https://caniuse.com/?search=prefers-color-scheme
like image 28
Ruskin Avatar answered Sep 02 '25 16:09

Ruskin