Adding a dark theme to your website
So, you want to add a dark (or light) theme to your website quickly and without destroying the code that you already have. This method works by taking the color theme settings from the device that is browsing your website and sending info to the browser and CSS about those color settings.
CSS Variables
For all of the colors that you would like to change between light and dark modes, you will have to set them as CSS variables. Setting CSS variables looks like this and can be changed for different classes or in this case media queries.
body {
--background-color: #000;
--text-color: #fff;
}
To call the variable after being set you have to follow the below code.
p {
color: var(--text-color);
}
Something that you should also add when calling CSS variables is adding a default fallback color for older browsers that can't handle CSS variables. When setting the fallback make it for the default color scheme if the device can't handle the @media (prefers-color-scheme: dark) {}
media query. Adding a fallback is as simple as the below.
p {
color: var(--text-color, #fff);
}
If you are using SCSS/SASS variables then you need to print the variable like this.
p {
color: var(--text-color, #{$white});
}
Prefers color scheme Media query
One of the newer media queries that have been added is the prefers-color-scheme media query. This checks for the color theme of the browsing device and can change styles based on that. The media query at its basics is shown below.
@media (prefers-color-scheme: dark) {
p {
color: red;
}
}
The options for the media query are: dark
, light
, and no-preference
. Side note, the light color scheme is the default if the device does not support this media query.