简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM