How to Display Mode-Specific Images

By  on  

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:

<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!

Recent Features

Incredible Demos

  • By
    Style Textarea Resizers

    Modern browsers are nice in that they allow you to style some odd properties.  Heck, one of the most popular posts on this blog is HTML5 Placeholder Styling with CSS, a tiny but useful task.  Did you know you can also restyle the textarea resizer in WebKit...

  • By
    Image Reflections with CSS

    Image reflection is a great way to subtly spice up an image.  The first method of creating these reflections was baking them right into the images themselves.  Within the past few years, we've introduced JavaScript strategies and CANVAS alternatives to achieve image reflections without...

Discussion

  1. A really simple little trick to work with. It should be fun to work with!

  2. 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.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!