Load a specific image depending on light/dark mode

Published on 08 September 2020 1 minute read (97 words)

You've implemented dark mode on your site, great! However, now you've found yourself stuck with a lot of images that may or may not fit into your overall design. No need to whip out that JavaScript - there's a native solution already built into HTML - <picture> tags.

I found myself facing the same problem when developing the front page for the site you're reading, and I wanted to avoid swapping images manually via JavaScript. Luckily the attribute specification for <source> tags (used inside of <picture> tags) states I can specify which file is for which media query:

<picture>
    <!-- Light mode images -->
    <source srcset="light.webp" media="(prefers-color-scheme: light)" type="image/webp">
    <source srcset="light.jpg" media="(prefers-color-scheme: light)" type="image/jpeg">

    <!-- Dark mode images -->
    <source srcset="dark.webp" media="(prefers-color-scheme: dark)" type="image/webp">
    <source srcset="dark.jpg" media="(prefers-color-scheme: dark)" type="image/jpeg">
  
    <!-- Fallback -->
    <img src="fallback.jpg" loading="lazy" alt="This is a fallback image" />
</picture>