Skip to main content

Command Palette

Search for a command to run...

Light and dark mode image in HTML

Published
1 min read
Light and dark mode image in HTML
C

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.

Did you know you can change images bases on the user 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 Prefer color scheme

HTML Structure

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

That's is it!

By default, it will 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.

Browser Support

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

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

S

This is awesome!!!!

2
C

Thank you Shreyasi! I'm glad you found this useful 🤟 And thanks for sharing this.

R

This is amazing 🤩

2
C

Hey Ritvik, cool this is supported in HTML right!

V

It's today's TIL for me.

3
C

Nice Vivek glad you learned something new today 🤟

More from this blog

D

Daily Dev Tips

887 posts

Looking to get into development? As a full-stack developer I guide you on this journey and give you bite sized tips every single day 👊