【问题标题】:Overwriting css root variables by adding a class to element [duplicate]通过向元素添加类来覆盖css根变量[重复]
【发布时间】:2022-07-10 02:43:54
【问题描述】:

我想创建一个暗模式,我想知道使用这种逻辑是否可以实现。也许用一些javascript或smth?或者它只是愚蠢的:)?所以在那种情况下,我有一些 js 切换按钮,它会给 body 一个 .night 类,这样会改变一个“光”做“暗”

 :root{

    --light: #ffffff;

}


.night :root{

    --light: #000000;

}

【问题讨论】:

  • :root 基本上等同于 html 元素,所以如果你将类添加到 body 选择器将是相反的方式。

标签: css root css-variables


【解决方案1】:

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

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

从逻辑上讲,: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');
});
/** 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>

详细了解CSS Custom Properties (variable)

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2023-03-22
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多