1

I have two different media query in a single stylesheet `

@media screen and (prefers-color-scheme: dark)

&

@media screen and (prefers-color-scheme: light)

`

this allows me to match the theme of my website to user system theme.

But i wanted to add a toogle switch that can override the system default and switch the dark media query to light

The DST
  • 31
  • 3
  • 1
    You can use a class on the `` or something like that to override the light/dark CSS rules, and then have your toggle add/remove the overriding class. – Pointy Dec 17 '22 at 14:36
  • I think this article should help: https://stackoverflow.com/a/56550819/18691321 – ninadepina Dec 17 '22 at 14:55

1 Answers1

1

Here is a solution for forcing dark theme since my system settings is light. You can easily edit to force light theme.

document.getElementById("forceDarkTheme").addEventListener("change", (e) => {
  if (e.target.checked) {
    document.body.classList.add("darkTheme");
  }
  else {
    document.body.classList.remove("darkTheme");
  }
});
@media screen and (prefers-color-scheme: light) {
  body:not(.darkTheme) {
    background: #CCCCCC;
    color: #333333;
  }
}

body {
  background: #333333;
  color: #CCCCCC;
}
<label>
  <span>Override system preference and use dark theme</span><input type="checkbox" id="forceDarkTheme" />
</label>

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

Second one which forces light theme:

document.getElementById("forceLightTheme").addEventListener("change", (e) => {
  if (e.target.checked) {
    document.body.classList.add("lightTheme");
  }
  else {
    document.body.classList.remove("lightTheme");
  }
});
@media screen and (prefers-color-scheme: dark) {
  body:not(.lightTheme) {
    background: #333333;
    color: #CCCCCC;
  }
}

body {
  background: #CCCCCC;
  color: #333333;
}
<label>
  <span>Override system preference and use light theme</span><input type="checkbox" id="forceLightTheme" />
</label>

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
burkay
  • 1,075
  • 1
  • 10
  • 20