Picture of me.

How to use CSS to set up an automatic dark mode

Hi!

Ok, so I wanted a dark mode on this website. Was tired of getting blinded at night when I went in here to check something.

(I have all my devices set up to automatic dark mode in the evening.)

Anyway, I looked it up and it’s super easy.

Note: This site uses SCSS, so you might need to modify this if you use something else, but I THINK this should work for normal CSS too.

Basically, we’re using CSS variables (ala --my-variable: myValue) to store values that need to change between dark and light mode and @media queries for performing the change based on system settings.

Step 1

Add CSS variables in the root element like this:

:root {
    --background-color: white;
    --text-color: black;
}

Step 2

Use a @media query to react to prefers-color-scheme and override the color variables for dark or light mode:

@media (prefers-color-scheme: dark) {
    :root {
        --background-color: black;
        --text-color: grey;
    }
}

(You can do @media (prefers-color-scheme: light) to override something for light mode.)

Step 3

Use the color variables in your styles like this:

html {
    background-color: var(--background-color);
    color: var(--text-color);
}

You can use these variables for the CSS of any other element too, like a {} or whatever.

 

Hope that helps someone in setting up their website!