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
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    CSS Tooltips

    We all know that you can make shapes with CSS and a single HTML element, as I've covered in my CSS Triangles and CSS Circles posts.  Triangles and circles are fairly simply though, so as CSS advances, we need to stretch the boundaries...

  • By
    Event Delegation with MooTools

    Events play a huge role in JavaScript. I can't name one website I've created in the past two years that hasn't used JavaScript event handling on some level. Ask yourself: how often do I inject elements into the DOM and not add an...

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!