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)
.