All Posts programming How to change an HTML image URL in dark mode ?

How to change an HTML image URL in dark mode ?

· 285 words · 2 minute read

Using CSS it’s pretty easy to apply changes if the system is in dark mode, using the prefers-color-scheme media feature.

Today I wanted to change images on my website according to the theme chosen. If the user prefer dark mode, dark theme will be enabled but I want to show a dark-mode images instead of the default light-mode ones.

But I want this to run from HTML not CSS nor Javascript. It can be done with HTML. Just use the picture tag to wrap the img tag and add a dark mode specific image with attribute media="(prefers-color-scheme: dark)" as you see in the code:

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

If dark mode is supported and enabled, the dark.png image will be used as the source for the img tag.

The tag is very well supported, and old browsers that do not implement it, or do not implement dark mode, will fall back to displaying the light.png image which is fine.

It’s important to note that the browser does not download 2 images, in any case: if it’s dark mode, in this example it will just download the dark.png image, and if it’s light mode, it will download only light.png, so there’s no waste of bandwidth. That’s a great scenario for SEO and UX.

I wrote another post about using different favicon for dark mode , check it out!

I hope you enjoyed reading this post as much as I enjoyed writing it. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , and GitHub .