I recently added a dark theme to this website. The theme is selected automatically based on the browser or OS settings. In this post, I'll describe how I implemented this.
Theme is selected based on browser settings
The first step is to extract all colors into CSS variables. While not mandatory, this simplifies creating the dark theme since you only need to override the variable values per 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);
}
Choose your colors carefully. If you're unsure which colors work well, look for inspiration from existing websites. For this website, I drew inspiration from learn.microsoft.com because it supports both light and dark themes. Also, ensure the contrast ratio is sufficient so text remains readable. The dev tools can help you pick colors with enough contrast:
Developer Tools - contrast ratio
To toggle between light and dark themes during development, use the emulation feature in the dev tools. Open the dev tools, 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!