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

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

  • By
    MooTools: Set Style Per Media

    I'd bet one of the most used MooTools methods is the setStyle() method, which allows you to set CSS style declarations for an element. One of the limitations of MooTools' setStyle() method is that it sets the specific style for all medias.

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!