DEV Community

Cover image for Automatic switching Dark/Light Mode
mrtoxas
mrtoxas

Posted on • Updated on

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

Top comments (0)