css - CSS 自定义属性和 CSS 变量之间有区别吗?

标签 css css-variables

在我在线阅读的所有资料中,CSS 自定义属性和 CSS 变量似乎是同一回事。但是,在 Inheritance of CSS Variables 中示例的末尾Mozilla Developer Network 文档的一部分,有一个令人困惑的声明:

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 自定义属性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) 引用的定义。就像一个变量!

quote continued...

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 自定义属性 视为与 CSS 变量 相同,但请务必记住,值是级联的,并且没有全局范围。

关于css - CSS 自定义属性和 CSS 变量之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48873595/

相关文章:

html - 背景大小不会改变 Firefox 中(左侧)线性渐变的高度

php - 使变量术语在出现在另一个变量中时具有自己的 CSS

javascript - 在滚动条上更改图像 Logo

css - CSS var() 后备在不受支持的浏览器中是否有效?

css - 如何调试 CSS calc() 值?

css - 媒体查询中的变量

javascript - 幻灯片的第一个元素不显示,按钮也不起作用

javascript - 如果可见性设置为隐藏,为什么 JavaScript 看不到

css - css 变量名可以以数字开头吗?

javascript - 从 JavaScript 访问 CSS 变量