Dark-Mode-Proof SVG Inside IMG

| tech

One feature of my static-site generator that I've been missing since I switched to hand-written HTML is automatic inlining of SVGs. Inlined SVGs can be styled with CSS like any other HTML element. This is especially useful for SVGs with transparent background and dark fill in dark mode. However, inlining SVGs manually is tedious and clutters the source code. So I now very much prefer IMG elements.

To prevent black fill on black background, I use the CSS filter property to invert the fill color in dark mode.

@media (prefers-color-scheme: dark) {
  img {
    filter: invert(0.8);
  }
}

The result doesn't match the text color 100% (see the musical score on this page), but it's good enough for me. For a perfect match, you could use hue-rotate, saturate, and sepia to tweak the color.

Another option would be to embed some CSS within the SVG that does a media query for the preferred color scheme, but then I'd need to hard-code the colors since I can't reference my CSS variables. The next time I change the color scheme of my site, all SVGs need manual updates. Yuck.