Variable SVG colors based on light/night mode

I have some SVGs that i display as images in my doc. Is it possible to have them so that the stroke is white for people with night mode and black for people with light mode?

Hi @Stian_Ovesen

It is possible to generate SVG code programatically, so it could have different strokes depending on some conditions.

But unfortunately there doesn’t seem to be a way to detect if someone is using dark mode or not.

1 Like

It is possible. Use a media query and style your SVG elements differently like this:

path {
  fill: black;
}

@media (prefers-color-scheme: dark) {
  path {
    fill: white;
  }
}

Please note that on Safari there’s a bug: prefers-color-scheme: dark will be ignored in SVG <img>'s regardless of whether the system is in dark or light mode. What I’m doing in that case is e.g. adding a plain white background to the whole SVG that’s only visible in Safari with this CSS hack:

#_bg {
  fill: #ffffff;
  fill-opacity: 0;
}

@supports (-webkit-hyphens:none) {
  #_bg {
    fill: #ffffff;
    fill-opacity: 1;
  }
}

...

<rect id="_bg" x="0" y="0" width="100%" height="100%" />
4 Likes

Thank you, Paul!

How do you implement this? Right now I’ve only dragged the SVG-files from my PC and straight into a page in a Coda-doc. Is that the wrong way to go about it?

1 Like

You edit the SVG files yourself. They are basically plain text files that follow XML syntax. They support CSS similar to HTML too.

Read MDN to learn more about SVG… or just ask your favorite AI to integrate these improvements into your svg files. Then you replace your SVGs in the doc with these new ones.

3 Likes