W3C

CSS Custom Properties for Cascading Variables Module Level 1

W3C Last Call Working Draft, 20 June 2013

This version:
http://www.w3.org/TR/2013/WD-css-variables-1-20130620/
Latest version:
http://www.w3.org/TR/css-variables-1/
Editor's Draft:
http://dev.w3.org/csswg/css-variables/
Previous Versions:
http://www.w3.org/TR/2013/WD-css-variables-20130312/
http://www.w3.org/TR/2012/WD-css-variables-20120410/
Feedback:
www-style@w3.org with subject line “[css-variables] … message topic …” (archives)
Editors:
Tab Atkins Jr. (Google)

Abstract

This module introduces cascading variables as a new primitive value type that is accepted by all CSS properties, and custom properties for defining them. CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, in speech, etc.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Last Call Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css-variables” in the subject, preferably like this: “[css-variables] …summary of comment…

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This specification is a Last Call Working Draft. All persons are encouraged to review this document and send comments to the www-style mailing list as described above. The deadline for comments is 18 July 2013.

Table of contents

1 Introduction

This section is not normative.

Large documents or applications (and even small ones) can contain quite a bit of CSS. Many of the values in the CSS file will be duplicate data; for example, a site may establish a color scheme and reuse three or four colors throughout the site. Altering this data can be difficult and error-prone, since it's scattered throughout the CSS file (and possibly across multiple files), and may not be amenable to Find-and-Replace.

This module introduces a family of custom author-defined properties known collectively as custom properties, which allow an author to assign arbitrary values to a property with an author-chosen name, and variables, which allow an author to then use those values in other properties elsewhere in the document. This makes it easier to read large files, as seemingly-arbitrary values now have informative names, and makes editing such files much easier and less error-prone, 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.

1.1 Module Interactions

This module defines a new type of primitive value, the variable, which is accepted by all properties.

1.2 Values

This specification follows the CSS property definition conventions from [CSS21]. Value types not defined in this specification are defined in CSS Level 2 Revision 1 [CSS21]. Other CSS modules may expand the definitions of these value types: for example if the <color> type was used in this specification, then [CSS3COLOR] would expand its definition.

2 Defining Custom Properties: the var-* family of properties

This specification defines an open-ended set of properties called custom properties, which are used to define variables.

Name:var-*
Value:<any-value>
Initial:(nothing, see prose)
Applies to:all elements
Inherited:yes
Computed value:specified value with variables substituted (but see prose for "invalid variables")
Media:all
Animatable:no

Should variables have special animation behavior, such that they just never animate, not even with the "just flip at 50% progress" like everything else?

Should the global values initial/inherit/default be interpreted? I'm guessing no, because we're not meant to interpret *anything*. You can get switch it back to inheriting by setting it to a guaranteed-invalid value, like var-foo: var(foo);, but you can't get default behavior.

What's the relationship of custom properties and the all property? Does it reset all the variables? If var-foo: initial; isn't interpreted by CSS, what effect does all: initial; have?

A custom property is any property whose name starts with "var-", and contains at least one additional character. Custom properties are solely for use by authors and users; CSS will never give them a meaning beyond what is presented here.

Note: Authors are recommended to choose custom property names so that the part after the "var-" is an identifier by itself, so that it can be referenced without character escaping. For example, var-0 needs to be referenced as var(\30), because 0 isn't a valid identifier. (U+0030 is the hexadecimal code for the 0 character.)

Custom properties define variables, referenced with the var() notation, which can be used for many purposes. For example, a page that consistently uses a small set of colors in its design can store the colors in custom properties and use them with variables:
:root {
  var-main-color: #06c;
  var-accent-color: #006;
}
/* The rest of the CSS file */
#foo h1 {
  color: var(main-color);
}

The naming provides a mnemonic for the colors, prevents difficult-to-spot typos in the color codes, and if the theme colors are ever changed, focuses the change on one simple spot (the custom property value) rather than requiring many edits across all stylesheets in the webpage.

Unlike other CSS properties, custom property names are case-sensitive. The "var-" prefix must be written in lower-case.

For example, VAR-FOO is invalid, because the prefix isn't "var-".

While both var-foo and var-FOO are valid, they are distinct properties - using var(foo) will refer to the first one, while using var(FOO) will refer to the second.

The allowed syntax for custom properties is extremely permissive. The <any-value> production matches any sequence of one or more tokens, so long as the sequence does not contain <bad-string>, <bad-url>, unmatched <<)>>, <<]>>, or <<}>>, or top-level <semicolon> tokens.

Note: This definition, along with the general CSS syntax rules, imply that a custom property value never includes an unmatched quote or bracket, and so cannot have any effect on larger syntax constructs, like the enclosing style rule, when reserialized.

Note: Custom properties can contain a trailing !important, but this is automatically removed from the property's value by the CSS parser, and makes the custom property "important" in the CSS cascade.

Note: While <any-value> must represent at least one token, that one token may be whitespace. This implies that var-foo: ; is valid, and the corresponding var(foo) call would have a single space as its substitution value, but var-foo:; is invalid.

For example, the following is a valid custom property:
var-foo: if(x > 5) this.width = 10;

While this value is obviously useless as a variable, as it would be invalid in any normal property, it might be read and acted on by JavaScript.

The values of custom properties, and the values of variables substituted into custom properties, are case-sensitive, and must be preserved in their original author-given casing. (Many CSS values are case-insensitive, which user agents can take advantage of by "canonicalizing" them into a single casing, but that isn't allowed for custom properties.)

The initial value of a custom property is an empty value; that is, nothing at all. This initial value has a special interaction with the var() notation, which is explained in the section defining var().

The primary purpose of custom properties is to define cascading variables. In CSS, a cascading variable is a value that can be substituted into other properties, allowing authors to "abstract" parts of their page's CSS out and reuse it in several places. Every custom property defines a corresponding variable with the same name, minus the "var-" prefix. For example, the custom property var-foo defines a variable named foo. See the next chapter for details on how to use variables.

Note: Custom properties can be put to several other uses, of course. For example, they can be used to conveniently attach values to elements so that JavaScript can later use those values. Another example is providing "custom CSS" by treating "var-" as a kind of "author prefix" (similar to a vendor prefix) that allows an author to write custom CSS properties without having them thrown away as invalid by the CSS parser, and then having JavaScript come along afterward to actually implement the functionality.

This style rule:
:root {
  var-header-color: #06c;
}

declares a custom property named "var-header-color" on the root element, and assigns to it the value "#06c". This property is then inherited to the elements in the rest of the document. Its value can be referenced via the "header-color" variable:

h1 { background-color: var(header-color); }

The preceding rule is equivalent to writing background-color: #06c;, except that the variable name makes the origin of the color clearer, and if var(header-color) is used on other elements in the document, all of the uses can be updated at once by changing the var-header-color property on the root element.

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules, can be made conditional with @media and other conditional rules, can be used in HTML's style attribute, can be read or set using the CSSOM, etc..

If a custom property is declared multiple times, the standard cascade rules help resolve it. Variables always draw from the computed value of the associated custom property on the same element:
:root { var-color: blue; }
div { var-color: green; }
#alert { var-color: red; }
* { color: var(color); }

<p>I inherited blue from the root element!</p>
<div>I got green set directly on me!</div>
<div id='alert'>
  While I got red set directly on me!
  <p>I'm red too, because of inheritance!</p>
</div>

Custom properties may use variables in their own values to build up composite variables. This can create cyclic dependencies where two or more custom properties each attempt to use the variable that the other defines; doing so makes all the custom properties involved in the cycle compute to their initial value (which is a guaranteed-invalid value).

This example shows a custom property safely using a variable:
:root {
  var-main-color: #c06;
  var-accent-background: linear-gradient(to top, var(main-color), white);
}

The var-accent-background property (along with any other properties that use var(main-color)) will automatically update when the var-main-color property is changed.

On the other hand, this example shows an invalid instance of variables depending on each other:
:root {
  var-one: calc(var(two) + 20px);
  var-two: calc(var(one) - 20px);
}

Both var-one and var-two now define invalid variables rather than lengths.

It is important to note that custom properties resolve any variables in their values at computed-value time, which occurs before the value is inherited. In general, cyclic dependencies occur only when multiple custom properties on the same element refer to each other; custom properties defined on elements higher in the element tree can never cause a cyclic reference with properties defined on elements lower in the element tree.

For example, given the following structure, these custom properties are not cyclic, and all define valid variables:
<one><two><three /></two></one>
one   { var-foo: 10px; }
two   { var-bar: calc(var(foo) + 10px); }
three { var-foo: calc(var(bar) + 10px); }

The <one> element defines a value for var-foo. The <two> element inherits this value, and additionally assigns a value to var-bar using the foo variable. Finally, the <three> element inherits the var-bar value after variable substitution (in other words, it sees the value calc(10px + 10px)), and then redefines var-foo in terms of that value. Since the value it inherited for var-bar no longer contains a reference to the var-foo property defined on <one>, defining var-foo using the var(bar) variable is not cyclic, and actually defines a value that will eventually (when referenced as a variable in a normal property) resolve to 30px.

3 Using Cascading Variables: the var() notation

Every custom property automatically defines a corresponding cascading variable, which can then be substituted into another property with the var() function. The syntax of var() is:

<variable> = var( variable-name [, <any-value> ]? )

A variable can be used in place of any part of a value in any property on an element. Variables can not be used as property names, selectors, or anything else besides property values. (Doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.)

The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the referenced variable is invalid.

Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(foo, red, blue) defines a fallback of red, blue; that is, anything between the first comma and the end of the function is considered a fallback value.

A property value containing a variable must be assumed to be valid at parse time. It is only syntax-checked at computed-value time, after variable references have been resolved.

To resolve a variable in a property's value:

  1. If the variable named by the first argument to the var() function is a valid variable, replace the var() function by the value of the corresponding custom property.
  2. Otherwise, if the var() function has a fallback value as its second argument, replace the var() function by the fallback value. If there are any var() references in the fallback, resolve them as well.
  3. Otherwise, the property containing the var() function is invalid at computed-value time.

    Note: Other things can also make a property invalid at computed-value time.

The fallback value allows for some types of defensive coding. For example, an author may create a component intended to be included in a larger application, and use variables to style it so that it's easy for the author of the larger application to theme the component to match the rest of the app.

Without fallback, the app author must supply a value for every variable that your component uses. With fallback, the component author can supply defaults, so the app author only needs to supply values for the variables they wish to override.

/* In the component's style: */
.component .header { 
  color: var(header-color, blue); 
}
.component .text { 
  color: var(text-color, black); 
}

/* In the larger application's style: */
.component {
  var-text-color: #080;
  /* header-color isn't set, 
     and so remains blue, 
     the fallback value */
}
For example, the following code incorrectly attempts to use a variable as a property name:
.foo {
  var-side: margin-top;
  var(side): 20px;
}

This is not equivalent to setting margin-top: 20px;. Instead, the second declaration is simply thrown away as a syntax error for having an invalid property name.

Similarly, you can't build up a single token where part of it is provided by a variable:

.foo {
  var-gap: 20;
  margin-top: var(gap)px;
}

Again, this is not equivalent to setting margin-top: 20px; (a length). Instead, it's equivalent to margin-top: 20 px; (a number followed by an ident), which is simply an invalid value for the margin-top property. Note, though, that calc() can be used to validly achieve the same thing, like so:

.foo {
  var-gap: 20;
  margin-top: calc(var(gap) * 1px);
}

A variable is substituted for its value in the property value at computed-value time. If a declaration, once all variables are substituted in, is invalid, the declaration is invalid at computed-value time.

For example, the following usage is fine from a syntax standpoint, but results in nonsense when the variable is substituted in:
:root { var-looks-valid: 20px; }
p { background-color: var(looks-valid); }

Since 20px is an invalid value for background-color, this instance of the property computes to transparent (the initial value for background-color) instead.

If the property was one that's inherited by default, such as color, it would compute to the inherited value rather than the initial value.

3.1 Invalid Variables

When a custom property has its initial value, the variable it defines represents an invalid variable. Using an invalid variable in a property value (including other custom properties) makes the declaration invalid at computed-value time.

A declaration can be invalid at computed-value time if it uses an invalid variable, as explained above, or if it uses a valid variable, but the property value, after substituting its variables, is invalid. When this happens, the computed value of the property is either the property's inherited value or its initial value depending on whether the property is inherited or not, respectively.

For example, in the following code:
:root { var-not-a-color: 20px; }
p { background-color: red; }
p { background-color: var(not-a-color); }

the <p> elements will have transparent backgrounds (the initial value for background-color), rather than red backgrounds. The same would happen if the variable itself was invalid.

Note the difference between this and what happens if the author had just written background-color: 20px directly in their stylesheet - that would be a normal syntax error, which would cause the rule to be discarded, so the background-color: red rule would be used instead.

Note: The invalid at computed-value time concept exists because variables can't "fail early" like other syntax errors can, so by the time the user agent realizes a property value is invalid, it's already thrown away the other cascaded values.

4 APIs

4.1 Extensions to the CSSStyleDeclaration Interface

The CSSStyleDeclaration interface is amended as follows:

partial interface CSSStyleDeclaration {
  readonly attribute CSSVariablesMap var;
}

A CSSStyleDeclaration is the associated style declaration for the CSSVariablesMap assigned to its var attribute.

While the CSSStyleDeclaration interface normally contains attributes that are camel-cased name variants of all CSS properties (and sometimes also attributes for their canonical names), it must not contain any such attributes for custom properties. The camel-case trick does not work, as custom property names are case-sensitive, and there are potentially an infinity of custom properties, which is incompatible with the normal behavior of exposing every property whether it was set in the corresponding declaration block or not.

4.1.1 Serializing Custom Properties

Custom property names must be serialized with the casing as provided by the author.

Ordinarily, property names are restricted to the ASCII range and are case-insensitive, so implementations typically serialize the name lowercased.

4.2 The CSSVariablesMap Interface

The CSSVariablesMap interface exposes the custom properties declared in the parent declaration block that have a non-initial value.

[MapClass(DOMString, DOMString)]
interface CSSVariablesMap {
  DOMString get(DOMString varName);
  boolean has(DOMString varName);
  void set(DOMString varName, DOMString varValue);
  boolean delete(DOMString varName);
}

The map tuples on a CSSVariablesMap object are the property names of all the custom properties in the CSS declaration block declarations with a non-initial value, with the "var-" prefix removed, paired with their values.

4.2.1 CSSVariablesMap Methods

get(DOMString varName), returns DOMString
Prepend "var-" to varName. Invoke getPropertyValue() on the associated style declaration by passing varName as its argument, and return its returned value.
has(DOMString varName), returns boolean
Invoke get() on the CSSVariablesMap object by passing varName as its argument. If the return value is the empty string, return false; otherwise, return true.
set(DOMString varName, DOMString varValue), returns void
Prepend "var-" to varName. Invoke setProperty() on the associated style declaration by passing varName and varValue as its two arguments, in that order.
delete(DOMString varName), return DOMString
Prepend "var-" to varName. Invoke removeProperty() on the associated style declaration by passing varName as its argument. If the returned value is the empty string, return false; otherwise, return true.

For example, given the following style sheet:

div {
  var-foo: 16px;
  var-Bar: red;
  var-foo-bar: 50%;
}

Here are the results of several JavaScript expressions, assuming that el is a JavaScript variable holding an element that the above style rule applies to:

Code Value Notes
el.style.var.get("foo") "16px" The value of var-foo.
el.style.var.get("Bar") "red" The value of var-Bar.
el.style.var.get("foo-bar") "50%" The value of var-foo-bar.
el.style.varFoo n/a Custom properties don't exist directly on "style"
el.style.varBar n/a Not even if the casing matches.
Iterating over all of the custom properties (for example, for a JS library to find the ones it knows about and wants to respond to) is also simple with the var property:
var customProps = el.style.var;
for(customPropName in customProps) {
  if( knownCustomPropName(customPropName) ) {
    var customPropValue = customProps[customPropName];
    /* Processing code here. */
  }
}

5 Changes from 10 April 2012 Working Draft

6 Acknowledgments

Many thanks to several people in the CSS Working Group for keeping the dream of variables alive over the years, particularly Daniel Glazman and David Hyatt. Thanks to multiple people on the mailing list for helping contribute to the development of this incarnation of variables, particularly Brian Kardell, David Baron, François Remy, Roland Steiner, and Shane Stephens.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words "for example" or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word "Note" and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Partial implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderers must treat as invalid (and ignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agents must not selectively ignore unsupported component values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Experimental implementations

To avoid clashes with future CSS features, the CSS2.1 specification reserves a prefixed syntax for proprietary and experimental extensions to CSS.

Prior to a specification reaching the Candidate Recommendation stage in the W3C process, all implementations of a CSS feature are considered experimental. The CSS Working Group recommends that implementations use a vendor-prefixed syntax for such features, including those in W3C Working Drafts. This avoids incompatibilities with future changes in the draft.

Non-experimental implementations

Once a specification reaches the Candidate Recommendation stage, non-experimental implementations are possible, and implementors should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group's website at http://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

References

Normative References

[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. URL: http://www.ietf.org/rfc/rfc2119.txt
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 7 June 2011. W3C Recommendation. URL: http://www.w3.org/TR/2011/REC-CSS2-20110607/

Informative References

[CSS3COLOR]
Tantek Çelik; Chris Lilley; L. David Baron. CSS Color Module Level 3. 7 June 2011. W3C Recommendation. URL: http://www.w3.org/TR/2011/REC-css3-color-20110607

Index

Property index

NameValueInitialApplies ToInh.%agesMediaComputed valueApplies toAnimatable
var-*<any-value>(nothing, see prose)yesallspecified value with variables substituted (but see prose for "invalid variables")all elementsno