Subscribe

Light and dark mode image in HTML

✍️

How to check if someone wants a light or dark image?

29 Oct, 2020 · 1 min read

Did you know you can change images based on the user’s preferred Color-scheme?

This nifty piece of code could already be used in CSS, but did you know it works directly in HTML?

We can detect if the user prefers a dark or light color schema and show a different image to them based on that!

It will look like this:

HTML Structure

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

That’s it!

It will default show the light image, but it will show the dark image if the person prefers the dark scheme.

Feel free to have a play with this on Codepen.

See the Pen Light and dark mode image in HTML by Chris Bongers (@rebelchris) on CodePen.

Browser Support

The support for prefers-color-scheme is getting better, but still not a reliable option.

CSS prefers-color-scheme support

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Submit button outside the form

4 Dec, 2022 · 1 min read

Submit button outside the form

Trying out native dialog modals

8 Aug, 2022 · 3 min read

Trying out native dialog modals

Join 2099 devs and subscribe to my newsletter