We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

带有前缀--的属性名,比如--example--name,表示的是带有值的自定义属性,其可以通过 var 函数在全文档范围内复用的。

CSS 自定义属性是可以级联的:每一个自定义属性可以多次出现,并且变量的值将会借助级联算法和自定义属性值运算出来。

初始值see prose
适用元素all elements
是否是继承属性yes
适用媒体all
计算值as specified with variables substituted
Animation typediscrete
正规顺序per grammar

语法

--somekeyword: left;
--somecolor: #0000ff;
--somecomplexvalue: 3px 6px rgb(20, 32, 54);
<declaration-value>
这个值将会由一个或者多个语法执行出来,只要这些语法是正确合理的,不包含非法语句。这个值就理应是有效语法执行出来的值。

正式语法

<declaration-value>

示例

HTML

<p id="firstParagraph">This paragraph should have a blue background and yellow text.</p>
<p id="secondParagraph">This paragraph should have a yellow background and blue text.</p>
<div id="container">
  <p id="thirdParagraph">This paragraph should have a green background and yellow text.</p>
</div>

CSS

:root {
  --first-color: #488cff;
  --second-color: #ffff8c;
}

#firstParagraph {
  background-color: var(--first-color);
  color: var(--second-color);
}

#secondParagraph {
  background-color: var(--second-color);
  color: var(--first-color);
}

#container {
  --first-color: #48ff32;
}

#thirdParagraph {
  background-color: var(--first-color);
  color: var(--second-color);
}

结果

规范

Specification Status Comment
CSS Custom Properties for Cascading Variables Module Level 1
--*
Candidate Recommendation Initial definition

浏览器兼容

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support491529 No36 Yes
var()

49

481

15

31

29 — 552 3

No36 Yes
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support4949152936 Yes5.0
var()50 ?15

31

29 — 552 3

37 Yes ?

1. From version 48: this feature is behind the Enable experimental Web Platform features preference. To change preferences in Chrome, visit chrome://flags.

2. From Firefox 29 until Firefox 31, this feature was implemented by the var-variablename syntax.

3. From version 29 until version 55 (exclusive): this feature is behind the layout.css.variables.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.

参阅

文档标签和贡献者

此页面的贡献者: zhangchen, Ende93, yisibl, Huooo
最后编辑者: zhangchen,