<div class="wrapper">
  <input type="checkbox" name="theme_switch" id="switch">
  <label for="switch">Toggle darkmode</label>
  <p>Cupcake ipsum dolor sit amet cake candy dessert.</p>
</div>
// define colors
$onyx: #404040;
$cultured: #f5f5f5;

// define themes
html[data-theme="light"] {
  --color-text: #{$onyx};
  --color-background: #{$cultured};
}

html[data-theme="dark"] {
  --color-text: #{$cultured};
  --color-background: #{$onyx};
}

// use colors
body {
  // just for presentation
  font-family: Arial;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 100vh;

  // here the css variables are used
  color: var(--color-text);
  background: var(--color-background);
}
View Compiled
let checkbox = document.querySelector("input[name=theme_switch]");

if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
  document.documentElement.setAttribute("data-theme", "dark");
  checkbox.checked = true;
} else {
  document.documentElement.setAttribute("data-theme", "light");
  checkbox.checked = false;
}

// switch theme if checkbox is engaged
checkbox.addEventListener("change", (cb) => {
  document.documentElement.setAttribute(
    "data-theme",
    cb.target.checked ? "dark" : "light"
  );
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.