Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting css root variables by adding a class to element [duplicate]

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;

}
like image 824
Wojtek Piskorz jr. Avatar asked Apr 16 '26 16:04

Wojtek Piskorz jr.


1 Answers

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

like image 190
ths Avatar answered Apr 19 '26 01:04

ths



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!