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
    39 Shirts &#8211; Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    NSFW Blocker Using MooTools and CSS

    One of my guilty pleasures is scoping out the latest celebrity gossip from PerezHilton.com, DListed.com, and JoBlo.com. Unfortunately, these sites occasionally post NSFW pictures which makes checking these sites on lunch a huge gamble -- a trip to HR's office could be just a click away. Since...

  • By
    CSS Scoped Styles

    There are plenty of awesome new attributes we've gotten during the HTML5 revolution:  placeholder, download, hidden, and more.  Each of these attributes provides us a different level of control over an element on the page, but there's a new element attribute that allows...

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!