CSS Color Scheme Queries (“Dark Mode CSS”)

Next to Safari 12.1 earlier this month, Firefox 67 now also supports “CSS Color Scheme Queries”.

The prefers-color-scheme media feature allows sites to adapt their styles to match a user’s preference for dark or light color schemes, a choice that’s begun to appear in operating systems like Windows, macOS and Android.

Chrome will support + enable it by default in Chrome 76 (the current Canary build at the time of writing)

~

Defining a “Dark Mode” for your websites becomes really easy when you combine prefers-color-scheme with CSS Custom Properties (“CSS Variables”):

:root {
    color-scheme: light dark;
    --special-text-color: hsla(60, 100%, 50%, 0.5);
    --border-color: black;
}

@media (prefers-color-scheme: dark) {
    :root {
        --special-text-color: hsla(60, 50%, 70%, 0.75);
        --border-color: white;
    }
}

.special {
    color: var(--special-text-color);
    border: 1px solid var(--border-color);
}

~

If you’re too lazy, then you can somewhat fake it by abusing mix-blend-mode: difference;, but it’s not perfect. Here’s an adjusted snippet, which injects the hack on the body using ::before:

@media (prefers-color-scheme: dark) {
    body::before {
        content: '';
        display: block;
        width: 100vw;
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        background: white;
        mix-blend-mode: difference;
        z-index: 1;
        pointer-events: none;
    }
}

~

A nice touch of Safari is that its DevTools also change when Dark Mode is enabled:

WebKit: Dark Mode Support in WebKit →
WebKit: Dark Mode Support in Web Inspector →Firefox 67: Dark Mode CSS, WebRender, and more →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

5 Comments

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.