How to add light and dark mode images to your GitHub repo README

How to add light and dark mode images to your GitHub repo README

Use this solution to specify the theme an image is shown to in a GitHub repository Readme file.

Let's say you want to beautify a GitHub repo README file—for example, the ✨ Special Repository ✨ that serves as the front page of your profile:

Screen Shot 2022-07-10 at 10.24.52 PM.png

In my case, I want to add the logos of my current and previous employers, but I need to ensure that they look good in both light and dark mode.

Basic images

For MUI, that's simple enough—the logo uses a cool blue color that looks great on light and dark backgrounds:

<img alt="MUI logo" src="https://user-images.githubusercontent.com/71297412/178181182-d024cbef-b80c-4790-a225-5bdb5aae2645.svg" height="125" />

Screen Shot of MUI logo in light mode

Screen Shot of MUI logo in dark mode

But if I take the same approach with the Hashnode logo, it doesn't work in dark mode:

<img alt="Hashnode logo" src="https://user-images.githubusercontent.com/71297412/178180441-59f1644e-2ab6-4bf0-866f-2c77b2a63433.png" height="25">

Screen Shot of Hashnode logo in light mode

Screen Shot of Hashnode logo in dark mode

Not great! 😵

Light and dark mode images

To solve this issue, GitHub introduced a way to specify the theme an image is shown to.

This solution uses the HTML <picture> tag in conjunction with the prefers-color-scheme media feature.

So for my Hashnode logo, I can give it one image with light text, and another with dark text, and then let the code sort it out based on the user's preference:

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/71297412/178180562-38f53e67-a31f-4c9f-b1a1-c9221703df4b.png">
  <source media="(prefers-color-scheme: light)" srcset="https://user-images.githubusercontent.com/71297412/178180441-59f1644e-2ab6-4bf0-866f-2c77b2a63433.png">
  <img alt="Hashnode logo" src="https://user-images.githubusercontent.com/71297412/178180441-59f1644e-2ab6-4bf0-866f-2c77b2a63433.png" height="25">
</picture>

Now, when I switch from light to dark mode on GitHub, the logo changes accordingly:

Screen Shot of samuelsycamore profile repo readme

Screen Shot of samuelsycamore profile repo readme

Pretty neat, right?

You can see it in action in my GitHub profile—feel free to give me a follow! 😇

💡 Before the introduction of the <picture> tag, GitHub used to let you specify themes for images using the fragments #gh-dark-mode-only and #gh-light-mode-only. These have since been deprecated and should no longer be used.


If you enjoyed this piece and you want to keep up with my work, you can sign up for my email newsletter through this link. I promise to make every email something you will be excited to open!

Did you find this article valuable?

Support Sam Sycamore by becoming a sponsor. Any amount is appreciated!