Skip to content

Instantly share code, notes, and snippets.

@symroe
Created November 3, 2024 15:36
Show Gist options
  • Save symroe/e821dc03a1f8c4c4392c5b47e410a7f1 to your computer and use it in GitHub Desktop.
Save symroe/e821dc03a1f8c4c4392c5b47e410a7f1 to your computer and use it in GitHub Desktop.

The aim

I want to support light and dark modes in my project.

I also want to have an 'inverted' mode, where I show a section of content in the opposite mode to the main site.

Set up

It's possible to use color-scheme: light dark; to enable the light and dark theme in my document, and then light-dark() to switch colours based on the active scheme:

html {
    color-scheme: light dark;
    background-color: light-dark(var(--white), var(--black));
}

(I use https://lightningcss.dev/ to convert this CSS to work in browsers that don't support light-dark, so I'm going to ignore browser support from here on in).

Invert styles

Inverting the colour scheme is as simple as setting the opposite colour scheme on the invert class:

@media (prefers-color-scheme: dark) {
    .invert {
        color-scheme: light;

    }
}

@media (prefers-color-scheme: light) {
    .invert {
        color-scheme: dark;

    }
}

This, with light-dark() means that the browser will pick the opposite scheme to the active one insite the invert class, with no need to specify the vars on the invert class at all.

Finially

It's possible that this is really obvious, but it was a new realisation to me and I thought others might like to know about it :)

I expect I should make one of those fancy intereactive things to show it off, but hopefully you get the idea without it :)

This might not be an excellent idea for eveyone :) My use case is to do a full-width 'breakout' section that's lightly used. I wanted something that would contrast with the rest of the site in both modes, and it seemed flipping the colour scheme was a neat way to do this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment