Adding a dark theme to your website with css variables

brettanda

Brett Anda ๐Ÿ”ฅ๐Ÿง 

Posted on January 27, 2020

Adding a dark theme to your website with css variables

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 send info to the browser and CSS about those color settings.

CSS Variables

All of the colors that you would like to change between light and dark mode you will have to set 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;
}
Enter fullscreen mode Exit fullscreen mode

To call the variable after being set you have to follow the below code.

p {
    color: var(--text-color);
}
Enter fullscreen mode Exit fullscreen mode

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 to 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);
}
Enter fullscreen mode Exit fullscreen mode

If you are using SCSS/SASS variables then you need to print the variable like this.

p {
    color: var(--text-color, #{$white});
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
brettanda
Brett Anda ๐Ÿ”ฅ๐Ÿง 

Posted on January 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About