Invert only specific color of SVG file

Hello everyone,

for some new decks i’m using svg images i’m extracting from a book. These are not only black and white, but also have some other colors in them, mostly light blue and orange. I’m mainly using Anki in night mode, so by standard i’m using

.nightMode img[src$=".svg"] {
    filter: invert(1);
}

in my styling. As it does what it says, it also inverts all other colors of the svg, which looks very odd.

Is it possible to convert only Black to White, and leave all the rest in it’s original color? I was thinking, maybe some deriviation of this Method 1? I thought, maybe replace the specific rgb value of the black with some white or just white, if the night mode is on? I would love to have the if, because if i share this deck with my fellow students, some may not use night mode, and would be confused why it looks odd.

Unfortunately I know nothing of javascript or css, and don’t really have the time to get into the basics to much, as already writing this post is a form procrastination…

It would be really generous if someone would help with this. Have my deepest thanks in advance.

Unfortunately i can’t upload an svg here, otherwise i would have provided an example. The rgb values in the svg are

<path fill="rgb(29,29,27)" # for the black
<path fill="rgb(218,87,59)" # for the orange
<path fill="rgb(46,135,167)" # for the blue

I think an easy way to accomplish something close to what you want is to append hue-rotate(180deg) to the filter. This will invert colors close to white or black, but maintain the hue of the other colors.

CSS

.nightMode img[src$=".svg"] {
    filter: invert(1) hue-rotate(180deg);
}

SVG file

<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
  <circle cx="100" cy="60" r="50" fill="rgb(29,29,27)" />
  <circle cx="50" cy="145" r="50" fill="rgb(218,87,59)" />
  <circle cx="150" cy="145" r="50" fill="rgb(46,135,167)" />
</svg>

( If you want to invert only a specific color other than black and white and not change the other colors at all, you will probably need to use Javascript. )

5 Likes

My dear person, this is perfect!

This does close enough what i envisioned, while totally maintaining my normal workflow, not requiring to much hacks :slight_smile: Thank you so much, i could have never imagined it could be so easy^^

1 Like