Ronalds Vilciņš

Dark mode images without JavaScript

You do not need JavaScript to swap an image for dark mode. The <picture> element accepts media queries on its <source> elements, including prefers-color-scheme.

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

When the visitor prefers dark mode, the browser uses dark.png. Otherwise it falls back to light.png from the <img> element.

Use a useful alt value when the image carries meaning. I left it empty here because the example is only about choosing the source.

Enjoyed reading this?

If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.

← Back to all articles