Load a specific image depending on light/dark mode

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>

Published in Code, Html


You might enjoy these as well

  1. Easy Typewriter effect/animation with Javascript
  2. React/Preact hook: usePersistedStore
  3. React/Preact hook: useEventListener
  4. Using Styled components with Preact
  5. Using Angular CLI with Laravel
  6. Deploy to Netlify via GitHub actions and "$ave Dat Money"
  7. Easily preserve any aspect ratio with pure CSS
  8. Easy Light and Dark mode switching with CSS