How to Display Mode-Specific Images
Publikováno: 4.5.2020
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 […]
The post How to Display Mode-Specific Images appeared first on David Walsh Blog.
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!
The post How to Display Mode-Specific Images appeared first on David Walsh Blog.