DEV Community

Cover image for How to add support for dark mode on your website
👨‍💻Ioannis Diamantidis
👨‍💻Ioannis Diamantidis

Posted on • Originally published at diamantidis.github.io

How to add support for dark mode on your website

In recent years, dark mode has grown in popularity as more and more devices and browsers are adding support for it.

Those reasons make it a great little feature that we can add on our websites to improve the experience of the users who prefer to use dark mode.

Let's see how we can support this feature in 3 steps!

First, we will take advantage of another great CSS feature: CSS variables

On the :root level, we will define two variables; one with the color of the background and one with the color of the text.

:root {
    --background-color: #FFF;
    --text-color: #000;
}
Enter fullscreen mode Exit fullscreen mode

Then, we will define a prefers-color-scheme media query for the dark color theme. In this media query, we will override the values of the variables that we defined in the previous step.

@media (prefers-color-scheme: dark) {
    :root {
        --background-color: #000;
        --text-color: #FFF;
    }
}
Enter fullscreen mode Exit fullscreen mode

Lastly, we will use those variables to assign their values to CSS properties. In our case, we will use the variable to set the background and the color of the body.

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

Now all you have to do is to find a color palette for the dark theme and apply it following those steps!


➡️ This post was originally published on my blog.

Top comments (3)

Collapse
 
saravananks profile image
SARAVANAN. K.S

What about the browser support?

Collapse
 
diamantidis profile image
👨‍💻Ioannis Diamantidis

Hey!! Most of the major browsers support this feature. If you want to find more about the browsers that support it and in which version they introduced it, you can take a look at this link caniuse.com/#search=prefers-color-...

Collapse
 
saravananks profile image
SARAVANAN. K.S

Agreed:)