DEV Community

Juhana Jauhiainen
Juhana Jauhiainen

Posted on • Edited on • Originally published at juhanajauhiainen.com

3 1

Dark mode using prefers-color-scheme rule and CSS variables

In this article I'll show you how to implement dark mode in your blog or site using CSS variables and how the toggle it automatically based on the users preferred color scheme.

CSS variables are a new way to make CSS more maintainable by defining reusable variables which are defined in one place and can be referenced in multiple other places.

For our dark mode example we'll be changing the sites background and text colors when the user has set dark mode as preference at system level.

So let's define our variables.

:root {
  --background-color: #1b1b1b;
  --text-color: #d0d0d0;
}
Enter fullscreen mode Exit fullscreen mode

Here we've defined two variables --background-colorand --text-color which we'll be using in our CSS definitions. They are added to the :root score so they are available globally.

But first we have to add a @mediaqueries with the prefers-color-schemerule to enable automatic color scheme selection based on the users settings.

@media (prefers-color-scheme: light) {
  :root {
    --background-color: #ffffff;
    --text-color: #000000;
  }
}

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

Now we're ready to use our CSS variables in our definitions.

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

Now the user should get the color scheme they prefer based on their system settings.

You can see this code in action on my personal website at juhanajauhiainen.com

If you liked this article and want to hear more from me, you can follow me on Twitter

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay