Adding dark theme to a website

 
 
  • Gérald Barré
 

I've recently added a dark theme to this website. The light or dark theme is selected based on the browser / OS settings. In this post, I'll describe how I've added this support!

Theme is selected based on browser settings

#Step 1: Extracting colors to variables

The first step is to extract all colors to variables. While this is not mandatory, it simplifies the creation of the dark. Indeed, you will only need to override the variable values depending on the theme.

CSS
:root {
    --color-primary: #000;
}

.sample {
    color: #000;
    color: var(--color-primary);
}

#Step 2: Add support for dark theme

Now you can override colors when the user prefers a dark theme. You can detect this by using the media query @media (prefers-color-scheme: dark).

CSS
:root {
    --color-primary: #000;
}

@media (prefers-color-scheme: dark) {
    :root {
        --color-primary: #fff;
    }
}

.sample {
    color: var(--color-primary);
}

You need to choose your color wisely. If you don't know which colors are great, you can take inspiration from existing websites. For this website, I get inspiration from learn.microsoft.com because it has light and dark themes. Also, you need to be sure the contrast ratio is good enough, so the text is readable. The dev tools can help you to choose colors with enough contrast:

Developer Tools - contrast ratio

If you want to switch from the light theme to the dark theme, you can use the emulation function in the dev tools. Open the dev tools and press ctrl+shift+P and select "Emulate CSS prefers-color-scheme: dark":

Developer Tools - Emulate CSS prefers-color-scheme

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub