在根而不是文档中添加 CSS 个变量(自定义属性)
Add CSS variables (custom properties) in the root not in the document
我正在使用 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;
}
而且效果很好。
我的问题是:
- 如何将从 ts 文件定义的其他变量设置为根而不是文档元素?
- 根据 post 根选择器比文档强。那么(如上图所示)我的根 primary-50 颜色如何被文档 primary-50 覆盖?
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
属性更高的特异性。
我正在使用 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;
}
而且效果很好。
我的问题是:
- 如何将从 ts 文件定义的其他变量设置为根而不是文档元素?
- 根据 post 根选择器比文档强。那么(如上图所示)我的根 primary-50 颜色如何被文档 primary-50 覆盖?
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
属性更高的特异性。