css 变量未应用于 body 标签

css variable is not get applied to body tag

我在我的 react 项目中使用纯 CSS 实现 dark mode 主题,为此,我使用 CSS 变量和 :root 伪-class。除了 --backgroundColor CSS 属性 标签的 --backgroundColor CSS 属性 之外,每种颜色都会反映在特定元素上,因此整个页面的背景颜色不会改变。你们能告诉我我错过了什么吗?

谢谢。

全局-styles.scss:

:root {
  --backgroundColor: #FFF;
  --text: #363537;
  --cardBackground: #fff;
  ........
}

[data-theme='dark'] {
  --backgroundColor: #23272f;
  --text: #e3e3e3;
  --cardBackground: #343a46;
  ........
}

body {
  font-family: 'Roboto', sans-serif;
  background: var(--backgroundColor);
}

*,
body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 16px;
}

h1 {
  font-size: 2rem;
  color: var(--text);
}

我认为问题在于您正在应用 data-theme 属性的元素

如果你将它应用到 body 那么它将起作用,例如参见 [​​=14=]

<body data-theme='dark'>
  <div>
    <h1>
      here
    </h1>
  </div>
</body>

如果您将标签应用于其他任何地方,它将不起作用

https://jsfiddle.net/18bnqhw4/

<div data-theme='dark'>
  <h1>
    here
  </h1>
</div>