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.
Related articles
- Making Links Easy to Recognize
Make links recognisable with underlines, clear focus states, useful text, and behaviour that does not surprise the reader.
- When CSS Layout Order Stops Matching the HTML
Keep Grid and Flexbox layouts aligned with the HTML order so keyboard focus and screen reader reading do not jump around the page.
- Keyboard Focus Styles With :focus-visible
Keep a clear keyboard focus indicator while avoiding the same focus ring after every pointer interaction.