通过向元素添加类来覆盖 css 根变量

1 css root css-variables

我想创建一个黑暗模式,我想知道是否可以使用这种逻辑来实现。也许用一些 javascript 或什么的?或者这只是愚蠢的:)?所以在这种情况下,我 ofc 有一些 js 切换按钮,可以为 body 提供 .night 类,从而将“light”更改为“dark”

 :root{

    --light: #ffffff;

}


.night :root{

    --light: #000000;

}
Run Code Online (Sandbox Code Playgroud)

ths*_*ths 6

选择:root器是html文档中封装所有网页的元素

:root CSS 伪类匹配表示文档的树的根元素。在 HTML 中,:root 代表元素,与选择器 html 相同,只是其特异性更高。 MDN 文档

从逻辑上讲,该:root元素是文档中最高的元素,因为它包含页面中的所有元素,因此我们不能有.some-selector :root选择器,因为html元素 ( :root) 没有父元素。

因此,要解决此问题,您可以将您称之为的类添加.night到root元素本身。这是一个快速演示。

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');
});
Run Code Online (Sandbox Code Playgroud)
/** 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;
}
Run Code Online (Sandbox Code Playgroud)
<button type="button" id="toggle">Toggle Night Mode</button>
<p class="demo">My background color will follow the selected theme (dark or light)</p>
Run Code Online (Sandbox Code Playgroud)

学习更多关于CSS Custom Properties (variable)。