0

I want to create a dark mode and I wonder if that'd be possible to achieve using this kind of logic. Maybe with some javascript or smth? Or is it just plain stupid :)? So in that scenario I ofc have some js toggle button that'd give a .night class to the body and with that would change a "light" do "dark"

 :root{

    --light: #ffffff;

}


.night :root{

    --light: #000000;

}
  • :root equates to the html element basically, so if you add the class to body the selector would be the other way round. – A Haworth Apr 15 '22 at 19:07

1 Answers1

4

The :root selector is the html element in the document which encapsulates all of your web page

The :root CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root represents the element and is identical to the selector html, except that its specificity is higher. MDN Docs

Logically, the :root element is the highest element in the document as it holds all the elements in the page thus we cannot have .some-selector :root selector because the html element (:root) doesn't have a parent element.

So to fix the issue, you can add the class, you called it .night, to the root element itself. Here's a quick demo.

const toggleBtn = document.getElementById('toggle');

toggleBtn.addEventListener('click', e => {
  e.preventDefault();
  /** toggle the ".night" class on the HTML element by accessing "document.documentElement" property */
  document.documentElement.classList.toggle('night');
});
/** default "--light" variable's value is "#fff" */
:root {
  --light: #fff;
}

/** when the "html" element has the ".night" class we change the "--light" variable's value to "#000" */
:root.night {
  --light: #000;
}

/** just for the demo nothing important */
.demo {
  background-color: var(--light);
  /** follows the "--light" value in real time */
  border: 4px solid red;
  padding: 4rem;
  text-align: center;
  color: red;
  font-size: 1.2rem;
  font-weight: bold;
}
<button type="button" id="toggle">Toggle Night Mode</button>
<p class="demo">My background color will follow the selected theme (dark or light)</p>

Learn more about CSS Custom Properties (variable).

ThS
  • 4,597
  • 2
  • 15
  • 27