Cooperweb.dev

Dark Mode with CSS Variables

headshot of Lee Cooper
Lee Cooper
The CSS Box Model
Dark Mode

Why Dark Mode?

Dark mode has become an increasingly popular option for websites. The ability to toggle between light and dark themes allows users to select a presentation that can reduce eye strain, improve device battery life, and match the aesthetic that the user prefers.

In this article, you'll learn how to implement dark mode for a website using CSS Variables so that you can begin to provide this feature to your users.

CSS Variables

The magic lies within CSS variables, which allows setting CSS values to a variable that can later be overwritten using Javascript.

For example, the above snippet sets a CSS variable (which can be named anything) on the root of the document and applies that variable to the body element's background-color, changing it to red. And since it's a variable, that means it can be changed.

Knowing this, a toggle function can be set up to replace the light mode values with their dark mode counterparts.

Lab: Implement Dark Mode with CSS Variables

To start out, create a basic HTML document with a heading, some paragraph text, and a button that will be used to toggle the theme of the page. Take note of the id attribute on the button - this will be used later in the javascript file.

Next, using the --variable-name: syntax, create styles for the background, text, and accent colors. Then use the var(--variable-name) syntax on the h1, p, button, and body elements. This sets our elements to pull color styling values from the new CSS variables, and sets us up for the final step.

Finally, attach a click event to the button via the button's id and toggle a .dark class on the root document element. When clicked, the :root will have the .dark class added, and because of its CSS specificity the dark mode values will be used in the document instead of the light mode values.

If everything is set up correctly, when the project is run and the button is clicked, the theme will successfully switch from light to dark mode! Check out the Stackblitz for a working demo of this.

The Possibilities Are Endless

This short article outlined an approach to implement light / dark mode themes, which can be further expanded to support other custom themes. From the functional and accessible high-contrast themes, to the outright fun cotton-candy bubblegum-esque themes, CSS variables provide developers with a powerful and simple method to switch app appearances at the click of a button.

Challenge:

Design and add another theme to the CSS file and provide a mechanism to toggle this new theme on/off. Did this introduce any issues with the dark mode theme? If so, why? Do the names of the CSS variables cause confusion when being applied to other elements? If so, how could this be addressed?