【问题标题】:Add CSS variables (custom properties) in the root not in the document在根而不是文档中添加 CSS 变量(自定义属性)
【发布时间】:2021-07-26 09:11:58
【问题描述】:

我正在使用 angular 12 并且我正在创建动态主题更改。

当我的应用程序根据所选主题加载时,我将所有颜色变量设置如下:

document.documentElement.style.setProperty(colorKey, colorValue);

之后,所有颜色都设置为文档元素而不是根元素。

如您所见,我还为根元素设置了一些变量。但是这些变量在 css 文件中定义为:

:root {
    --primary: #005d7a;
    --primary-50: #edf1f2;
    --primary-400: #0094bd;
    --primary-700: #027498;
    --secondary-50: #ffebb7;
    --silver: #3a3a3a;
    --silver-light: #e4e7ea;
    --silver-light-border: #dad7d6;
    --main-background: white;
    --main-page-background: #e4e7ea;
    --main-text-color: #3a3a3a;
    --disabled-color: #ccc;
}

而且效果很好。

我的问题是:

  1. 如何将 ts 文件中定义的其他变量设置到根而不是文档元素?
  2. 根据post 根选择器比文档强。那么(如上图所示)我的根 primary-50 颜色如何被文档 primary-50 覆盖?

【问题讨论】:

  • 内联样式永远赢
  • 而 html 是 :root 元素

标签: html css css-variables


【解决方案1】:

document 上没有设置任何内容。 The documentElement is the root element.

您有一个样式表,可以在 :root, which is the html element in an HTML document 上设置一些东西。

即CSS 中的 :root 与 DOM 中的 document.documentElement 定位相同的元素。


html 元素(同一个元素)上有一些内联样式(style 属性)。

Cascading rules 赋予 style 属性中的规则优先于所有其他同等重要且来自同一来源的规则。

您引用的文档说选择器:root 比选择器html 具有更高的特异性。它们都没有比style 属性更高的特异性。

【讨论】:

  • 感谢您的精彩解释。每当我阅读如何更改根 CSS 变量的值时,我都会得到相同的答案:document.documentElement.style.setProperty(colorKey, colorValue)。这对我来说是令人困惑的部分。如果我想更改根 CSS 变量与将内联 CSS 变量添加到文档元素的代码相同?
  • 我不知道你现在想问什么。
  • 如何更改我在 CSS 中定义的(例如:)root { primary } 变量的值?不向文档添加内联样式...
  • 我的全部观点是,如果可能的话,我不想将这些样式视为内联样式。
猜你喜欢
  • 2016-02-26
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 2018-08-09
相关资源
最近更新 更多