How to Display Mode-Specific Images
Now that we have most of the basics of HTML and CSS in the browser, we've begun implementing new features that I would consider "quality of life" improvements, many of which have been inspired by mobile. One great example is the CSS prefers-color-scheme media query, which allows developers to cater their design to system theme (dark or light) preference:
/* Light mode */ @media (prefers-color-scheme: light) { html { background: white; color: black; } } /* Dark mode */ @media (prefers-color-scheme: dark) { html { background: black; color: white; } }
While watching my Twitter feed fly by, I saw an awesome trick from Flavio Copes:
A little HTML trick you can use to show a different image in dark mode pic.twitter.com/yyFIGAPRcA
— flavio (@flaviocopes) April 27, 2020
<picture> <source srcset="dark-logo.png" media="(prefers-color-scheme: dark)"> <img src="logo.png" /> </picture>
By applying the media query to the source, you can define the image to load. This technique is obviously valuable when you need to load a new source image and not simply change a CSS property.
Maybe not the most maintainable code but very clever nonetheless!
A really simple little trick to work with. It should be fun to work with!
Note that this is quite new feature. IE doesn’t support it at all. Chromium supports it from version 76, so it was implemented quite recently there.