Warning
This no longer seems to work. And GitHub has added built-in support this: https://github.com/stefanjudis/github-light-dark-image-example#a-test-for-lightdark-mode-images-using-picture
This gist demonstrates how a light/dark-mode image can be rendered in GitHub markdown. The image of the square below will be dark-blue when your computer prefers dark-mode, and will be bright-yellow if your computer prefers light-mode.
It leverages SVG foreignObject
to use the CSS media query prefers-color-scheme: dark
to determine which element to show.
In this case, it has two image assets (light & dark versions) Base64'd, but can probably be replaced with a SVG too.
- Toggling light/dark-mode is not reactive. After toggling the system setting, reload the page. If it doesn't work, try checking "Disable cache" in the Chrome devtools Network tab.
- There cannot be external assets (eg.
<img>
tag referencing an external file). Use Base64 instead.
Update
GitHub Markdown now supports an official way to toggle between two images in light/dark mode.
That's good to know. Thank you. I knew about the anchors, but it seems those are being deprecated. That said, in these cases we have SVGs that only vary based on the
@media
queries within embedded<style>
sheets. I'd hate to have to duplicate the entirety of the SVGs just to select one over another when 99.999% of the content is exactly the same.I did file a feedback issue with Apple Feedback citing this gist and a few other repros. FWIW, GitHub.com is sending a
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
header so it should work, and does work for me in Edge/Chromium e.g., the preview pane in VSCode renders correctly on a dark theme.