Skip to content

Light and Dark Mode Images in GitHub Markdown

GitHub renders Markdown with either a light or dark theme depending on the user's system or GitHub appearance settings. A logo or diagram that looks sharp on a white background can disappear entirely when the same user switches to dark mode. GitHub provides two ways to serve the correct image for each theme without JavaScript.

If you are using MkDocs Material, the same problem has a pure-Markdown solution covered in a companion post: Light and Dark Mode Images in MkDocs Material.

HTML with URL Fragments

GitHub's Markdown renderer recognizes two special URL fragments on <img> tags:

Fragment When It Renders
#gh-dark-mode-only Only shown when the user is in dark mode
#gh-light-mode-only Only shown when the user is in light mode

These fragments are used with plain HTML <img> tags inside a Markdown file. GitHub's renderer allows inline HTML, so this works in any .md file on GitHub. This is the pattern used in the .github repository README:

<!-- dark mode -->
<img src="docs/images/logo-dark.png#gh-dark-mode-only" alt="tenthirtyam"/>
<!-- light mode -->
<img src="docs/images/logo-light.png#gh-light-mode-only" alt="tenthirtyam"/>

When a GitHub user with dark mode enabled views the file, they see the dark variant. When light mode is active, they see the light variant. GitHub hides the inactive image entirely; it does not just reduce its opacity.

Comments Are Optional

The <!-- dark mode --> and <!-- light mode --> comments are for readability only. They have no effect on rendering and can be omitted.

The <picture> Element

The <picture> element with a prefers-color-scheme media query is a more portable option. It follows the HTML specification and works in GitHub Markdown as well as any other renderer that allows inline HTML:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/images/logo-dark.png" />
  <img src="docs/images/logo-light.png" alt="Logo" />
</picture>

The <source> element is applied when the dark color scheme is active. The <img> element serves as the fallback for light mode and for rendering environments that do not support the <picture> element, such as email clients and RSS readers.

Which to Use

Both approaches work in GitHub-rendered Markdown. The <picture> element is the more standards-compliant choice and degrades gracefully. The #gh-dark-mode-only and #gh-light-mode-only fragments are GitHub-specific and will not work outside of GitHub-rendered content.

Note

Neither approach uses the standard ![]() Markdown image syntax. Both require writing inline HTML directly in the Markdown file.