Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change image source based on CSS prefers-color-scheme?

Tags:

html

css

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?

like image 978
Charlie Fish Avatar asked Apr 21 '19 22:04

Charlie Fish


1 Answers

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>
like image 57
Charlie Fish Avatar answered Sep 28 '22 17:09

Charlie Fish