'How to trigger prefers-color-scheme in :root and for global variable?

I have written css code similar to this:

:root {
  ...some global color related variables
}

@media (prefers-color-scheme: dark) {
  :root {
    ...global colors are overwritten
  } 
}

and I have a button that toggles between dark mode and light mode which its javascript code works like this:

document.documentElement.style = `color-scheme: ${mode};`; // mode is either light or dark
const meta = document.querySelector('meta[name="color-scheme"]');
meta.content = mode; // mode is either light or dark

And it applies its style which is color-scheme: light or dark to the html element and all of the other elements as well, but it doesn't trigger the prefers-color-scheme in the styles related to the :root and global variables or even some other places. How can I be able to do this?


PS1: When I change the color scheme of the website using chrome browser itself (using Emulate CSS prefers-color-scheme: dark in dev tools) it works just fine and the global variables get overwritten.

PS2: I'm trying to implement dark mode using color schemes and avoid having to add a class or anything like that and It's because of some default styling of the browsers that gets applied thinking it's a light moded website which isn't (like -internal-light-dark color in auto-filling an input)



Solution 1:[1]

I think the solution you're looking for is adding the media query after the root like this:

:root {
  ...some global color related variables
}

@media (prefers-color-scheme: dark) {
  :root {
    color-scheme: dark;
    /* variable overrides ... */
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 flaming.codes