【问题标题】:css variable is not get applied to body tagcss 变量未应用于正文标签
【发布时间】:2022-01-09 02:06:26
【问题描述】:

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

谢谢。

全局样式.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);
}

【问题讨论】:

  • 您是否使用浏览器开发工具检查了 body 元素,看看它是否可以从具有更高特异性的不同规则或类似的东西中应用其背景颜色?

标签: html css reactjs sass


【解决方案1】:

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

如果你将它应用到body 那么它将起作用,例如参见https://jsfiddle.net/mg1bhrqj/

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

如果您将标签应用到其他任何地方,它将无法正常工作

https://jsfiddle.net/18bnqhw4/

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多