DEV Community

Cover image for Automatic switching Dark/Light Mode
mrtoxas
mrtoxas

Posted on • Edited on

4 1

Automatic switching Dark/Light Mode

Much has been said about switching the dark/light mode of a web page, but let's try switching themes automatically, depending on the selected theme in the operating system.

Let's start by defining the basic styles:

:root {
  --text-color: black;
  --body-bg: white;
}

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

Now we are adding the preferences-color-scheme media function to define the system theme. And according to the chosen theme we will change the root-variables:

@media (prefers-color-scheme: dark) {
  :root {
    --text-color: white;
    --body-bg: black;
  }
}
Enter fullscreen mode Exit fullscreen mode

Now when the user changes the system theme to black, we get white text on a black background.

We can also define values for a light theme using the "light" value.

Support for this method is not yet 100%, some browsers are still lagging behind progress. Therefore, do not rush to remove the button to switch themes. But nothing prevents you from using this magic right now.

Happy coding!

Sources for reading:
Using CSS custom properties
prefers-color-scheme

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more