Switch SVG colors automatically in light/dark modes #7717
-
Hello! I'd like to include some SVG diagrams into my documentation page. These diagrams are quite simple: something like this I use "currentColor" inside SVG to make stroke color automatically switch for light/dark mode, how it is done for icons normally. So I do not need to mantain two copies of the same diagram. However, I could't manage to incude such image to page properly and make it work (diagram color follows text color). Could you please help me? Is this even possible? Upd. I've read "Light and Dark mode" paragraph, but I'd like to avoid having multiple copies of the same SVG. Upd. I've found this discussion #2097, but there is suggested to store and render SVG as custom icon, which, I suppose, won't work with large diagrams, because size is going to be reduced. Need to check though. Upd. Okay, it looks like SVG has to be embedded into HTML via |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
Hi, this definitely works (I use a lot of custom icons). |
Beta Was this translation helpful? Give feedback.
-
Hello @esynr3z, But as you're working with simple shapes and only want to match the light/dark mode you can do so using CSS and the filter: invert setting to change the color from the default black to white. This is used in the emoji search box in the docs, you can check the web tools. |
Beta Was this translation helpful? Give feedback.
-
Thank you, @kamilkrzyskow! I'll definitely try filter option. Use of For anyone interested, this works fine, because it is just text:
Below also works, but you need to know a lot of internal details of referenced SVG like
I suppose macro plugin can fix using of Another option is to go with two images, but generate them via script using common source and replace all |
Beta Was this translation helpful? Give feedback.
-
So, I went with filter and it works like a charm! Thank you @kamilkrzyskow again! Full recipe:
img.invert-on-slate {
filter: invert(0);
}
[data-md-color-scheme="slate"] img.invert-on-slate {
filter: invert(1);
}
<img src="/assets/images/flow.drawio.svg" alt="Program Flow" class="invert-on-slate"> Note: I use draw.io for diagrams and save the diagram as "editable SVG", so I can edit nodes and connections in the software anytime and make it looks like a valid SVG elsewhere. |
Beta Was this translation helpful? Give feedback.
Hello @esynr3z,
as you've pointed out in the edit, to support the
fill: currentColor
for the SVG, they need to be included via the HTML<svg>
tag.SVGs are plain text files and you should be able to include them using the macros plugin.
But as you're working with simple shapes and only want to match the light/dark mode you can do so using CSS and the filter: invert setting to change the color from the default black to white.
This is used in the emoji search box in the docs, you can check the web tools.