在我在网上阅读的所有资料中,似乎CSS自定义属性和CSS变量是相同的.但是,在Mozilla Developer Network文档的Inheritance of CSS Variables部分中的示例结尾处,有一个令人困惑的声明:
Keep in mind that these are custom properties,not actual CSS
variables. The value is computed where it is needed,not stored for
use in other rules. For instance,you cannot set a property for an
element and expect to retrieve it in a sibling’s descendant’s rule.
The property is only set for the matching selector and its
descendants,like any normal CSS.
这让我觉得这两个概念不是同义词.
他们对页面标题没有错:Using CSS custom properties (variables)
然而,CSS变量不是传统意义上的变量,因为没有办法定义它以使其像编程语言或CSS预处理器(LESS / Sass)一样全局范围.
即使是根作用域的自定义属性/变量也不是全局的.更改子项中属性的值不会更改上面的值或该范围的兄弟节点.如果有人期望是全球性的,那么可能会引起混淆,我怀疑这就是Mozilla的作者试图指出的.
如果你看看
w3.org’s CSS Custom Properties for Cascading Variables
This module introduces a family of custom author-defined properties known collectively as custom properties
自定义属性是可以使用var( – my-custom-prop)引用的定义.像一个变量!
as one only has to change the value once,in the custom property,and the change will propagate to all uses of that variable automatically.
尴尬……上述陈述并不完全正确.似乎Mozilla开发者网络文档正试图澄清这个想法,以免它变得混乱. Repeating the original quote:
Keep in mind that these are custom properties,not actual CSS variables. The value is computed where it is needed,not stored for use in other rules. For instance,you cannot set a property for an element and expect to retrieve it in a sibling’s descendant’s rule. The property is only set for the matching selector and its descendants,like any normal CSS.
他们指出它不是传统意义上的编程语言的变量.但它的计算就像样式一样,遵循CSS的一般级联/范围规则.
因此var( – my-custom-prop)可以根据声明的位置解析为非常不同的东西,并且声明不会传播到更高的范围.
如果您想尝试一下,这是a codepen to mess around with.
因此,将CSS Custom Property视为与CSS Variable相同,但请务必记住值级联,并且没有全局范围.