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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

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

Okay