Skip to content

Instantly share code, notes, and snippets.

@privatenumber
Last active December 14, 2022 19:58
Show Gist options
  • Save privatenumber/0b3db759ca8c90103360603ff3d49893 to your computer and use it in GitHub Desktop.
Save privatenumber/0b3db759ca8c90103360603ff3d49893 to your computer and use it in GitHub Desktop.
Light/dark mode SVG image

Light/Dark image in GitHub markdown

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.

How does it work?

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.

Caveats

  • 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.

Demo

Update

GitHub Markdown now supports an official way to toggle between two images in light/dark mode.

Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@pboling
Copy link

pboling commented Apr 12, 2022

This solution doesn't seem to work at all for me. I always see the blue, no matter the system dark mode setting or the Github dark mode setting. I've tried many variations, but can't get anything to fully work:
https://gist.github.com/pboling/3bd9a0004b8fc010c0d7c523fecee832

@privatenumber
Copy link
Author

Works fine for me.

Light Dark

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment