Render Images Based On Dark or Light Theme Of The Device
If your website has been equipped with a dark theme, there will be a good chance where you might want to render some of the images based on the device’s theme. i.e. Dark or Light theme.
To, the common way using which you can render an image is by using an <img>
tag and in this article, I’m going to discuss the HTML-based approach to achieve this problem.
Let’s say, you’re already rendering an image like so.
<img
src="https://picsum.photos/id/1035/300"
alt="Light Mode Image"
>
Now, you want this image to be something else when the user has Dark mode/theme turned on his/her device. How would you do that?
Well, this can be achieved through the combination of using the <source>
element and a pinch of a media query.
So, here’s how we can do this.
<picture>
<source
srcset="https://picsum.photos/id/1019/300"
media="(prefers-color-scheme: dark)"
>
<img
src="https://picsum.photos/id/1035/300"
alt="Light Mode Image"
>
</picture>
As you can tell, for this to work, we need to use a <source>
element (enclosed by a <picture>
element) on which we can specify the image that we want to render when the device has a dark theme turned on. This will be determined by specifying a media
attribute and setting it as (prefers-color-scheme: dark).
If the device has a light theme turned on, the user agent will fall back to the image given by the <img>
element.
You can see it in action in the CodePen below.
Open the CodePen in the new tab and try changing the device’s theme (or simulate it from the dev tools) and watch out for the image!
See the Pen Change Images Based On Light/Dark Mode by Amit Merchant (@amit_merchant) on CodePen.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.