I'm trying to integrate the new CSS prefers-color-scheme
media query into my website. I have an img
(image) element where the image is very dark blue. Which looks really bad with the new dark mode setting.
Is there a way to easily to change the source of this image based on that CSS media query?
I have considered having 2 img
elements and set the display
to hidden or not depending on that media query. But that feels like a little bit of a messy solution, and has it's drawbacks, such as the browser downloading both images.
I've also considered doing a CSS trick with background-image
but I'm even more opposed to that than having 2 img
elements and hiding and showing them.
Finally, of course I think this is possible using JavaScript. But this site specifically I'm very considered about compatibility, and some browsers allow users to turn off JavaScript all together, so a JavaScript solution I'm not a fan of in this case.
Is there any other way to do what I want here other than those solutions listed above?
According to the WebKit blog you can use the HTML picture
tag to achieve this behavior.
Something like the following code is setup to use night.jpg
when the color scheme is set to dark, but default to day.jpg
.
<picture>
<source srcset="night.jpg" media="(prefers-color-scheme: dark)">
<img src="day.jpg">
</picture>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With