How to change an HTML image URL in dark mode ?

· 227 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 (a.k.a User Experience).

Read more : different favicon for dark mode

Share:
waffarx cash back