Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, in speech, etc. This module contains the features of CSS level 3 relating to variables. It includes and extends the functionality of CSS level 2 [CSS21], which builds on CSS level 1 [CSS1]. The main extensions compared to level 2 are the introduction of the variable as a new primitive value type that is accepted by all properties.
This is a public copy of the editors' draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don't cite this document other than as 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 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 variable 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, at the variable definition site, and the change will propagate to all uses of that variable automatically.
This module defines a new type of primitive value, the variable, which is accepted by all properties.
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 [CSS3COLOR], when combined with this module, expands the definition of the <color> value type as used in this specification.
This specification defines an open-ended set of properties called variable properties, which are used to define variables.
| Name: | var-* |
|---|---|
| Values: | <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 |
The <value> type used in the syntax above is defined as anything matching the "value" production in CSS 2.1 Chapter 4.1 [CSS21]. This puts almost no restrictions on what kinds of values you can store in variables. Obviously, any valid property value or component of a property is allowed. Additionally, this allows things that aren't yet valid CSS, like unknown keywords or functions, blocks, at-rules, and other kinds of custom micro-syntaxes like what's allowed in calc(). There are still rules, however; for example, unbalanced parentheses are invalid.
The term variable property refers to any property whose name is composed of a "var-" prefix followed by something matching the IDENT production in CSS2.1 Chapter 4. A variable property defines a value for a corresponding variable with the same name as the property except that the "var-" prefix is replaced with a "$" prefix.
The initial value of a variable property is an empty invalid value. This means that, until a variable property is explicitly defined otherwise by a style sheet, it defines an invalid variable
As defined here, the syntax for variable usage is different from the syntax for variable definition (i.e. var-foo for definition, $foo for usage). It might be nice to have the syntaxes match, using "$foo" as the property name as well. This would require a minor change in the Core Grammar.
Variable properties are defined to be valid but meaningless as they are meant solely for allowing authors to pass custom data around their page, similar to the custom data attributes in HTML. Other specifications and user agents must not assign a particular meaning to variable properties or attach a specific effect to them beyond the bare minimum that comes from them being valid properties.
For each variable property, there is an associated variable with the same name save for the "var-" prefix. For example, a variable property named "var-foo" is associated with the variable named "foo". See the next chapter for details on how to use variables.
This style rule:
:root {
var-header-color: #06c;
}
declares a variable 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: $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.
Variable 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 variable property is declared multiple times, the standard cascade rules help resolve it. Variables always draw from the computed value of the associated variable property on the same element:
:root { var-color: blue; }
div { var-color: green; }
#alert { var-color: red; }
* { color: $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>
Variable properties may use variables in their own values to build up composite variables. This can create cyclic dependencies where two or more variable properties each attempt to use the variable that the other defines; doing so makes all the variable properties involved in the cycle compute to their initial value (which is a guaranteed-invalid value).
This example shows a variable property safely using a variable:
:root {
var-main-color: #c06;
var-accent-background: linear-gradient(to top, $main-color, white);
}
The ‘var-accent-background’ property
(along with any other properties that use ‘$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($two + 20px);
var-two: calc($one - 20px);
}
Both ‘var-one’ and ‘var-two’ now define invalid variables rather than
lengths.
It is important to note that variable 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 variable properties on the same element refer to each other; variable 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 variable properties are not cyclic, and all define valid variables:
<one><two><three /></two></one>
one { var-foo: 10px; }
two { var-bar: calc($foo + 10px); }
three { var-foo: calc($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’.
A variable allows the value of a variable property on an element to be
substituted into another property on the element. There are several ways
to use variables: by name, via the ‘var()’
notation, or via the ‘parent-var()’ notation to
get at a variable on the element's parent.
A variable can be used in place of any component value in any property on an element. Variables can not be used as property names, selectors, or anything else besides property values - doing so either produces an invalid value or, in some situations like the attribute value of an attribute selector, produces a valid value that nonetheless has no relation to the variable of that name.
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: $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.
The simplest way to use a variable is to refer to it by its name, which is the same as the variable property defining it, except with the "var-" prefix swapped out for a "$" prefix. Formally, the syntax of a variable is:
<var> = "$" IDENT
...where IDENT is anything matching the IDENT production in CSS2.1 Chapter 4.
For example, the following code defines and uses a variable named "main-color".
:root {
var-main-color: blue;
}
h1 {
color: $main-color;
}
var()’ notationIn some cases, it can be useful to provide a "default" value for a variable in case the variable isn't defined or is invalid.
For example, if a site uses variables to provide "hooks" for customization, expecting the variables to be defined in a separate custom stylesheet, the main stylesheet can use default values for its variable so that the theming stylesheet can just override the variables it cares about, rather than being forced to provide values for all of them.
The ‘var()’ notation allows a default value
to be specified when referencing a variable. The syntax of ‘var()’ is:
<default-var> = var( <var> [, <value> ]? )
If the variable named by the first argument is valid, the variable's
value is substituted as normal. If it's invalid, and a second argument was
provided, the value of the second argument is substituted instead.
Otherwise, the ‘var()’ represents an invalid variable.
Note that using ‘var()’ without a
second argument offers no benefits over using the variable by itself. This
is allowed for consistency with ‘parent-var()’,
which does do something useful with only one argument. Future
variable functions will likely be similar.
parent-var()’ notation Several advanced use-cases for variables need the ability to reference
the value that a variable has on the element's parent, rather than on the
element itself. This can be accomplished with the ‘parent-var()’ notation:
<parent-var> = parent-var( <var> [, <value> ]? )
If the element has a parent, and the variable named by the first
argument is valid on the parent, the variable's value on the parent is
substituted as normal. Otherwise, if a second argument was provided, the
value of the second argument is substituted instead. Otherwise, the
‘parent-var()’ represents an invalid variable.
For example, ‘parent-var()’ can be used to
implement a behavior that's very similar to the ‘toggle()’ notation from [[CSS3VALUES]]. In this
example, each nested comment alternates between a white and silver
background.
<div class='comment'>
<div class='main'>
...
</div>
<div class='actions'><a>Reply</a> <a>Comment</a> ...</div>
</div>
<div class='comment'>
<div class='main'>
<div class='comment'>
<div class='main'>
...
</div>
<div class='actions'><a>Reply</a> <a>Comment</a> ...</div>
</div>
</div>
<div class='actions'><a>Reply</a> <a>Comment</a> ...</div>
</div>
<style>
.comment {
var-bg: parent-var($bg2, white);
var-bg2: parent-var($bg, silver);
background: url(comment.png) $bg;
}
</style>
The ‘toggle()’ notation can't be used here,
because ‘background-color’ isn't
inherited (and thus the nested comments see the initial value of ‘transparent’ rather than ‘white’ or ‘silver’). Even
if the author explicitly sets ‘background-color:inherit’ on <div
class='main'> so that ‘toggle()’ can
actually see the right value, that will make the ".main" elements cover
up the ‘background-image’ that ".comment"
has on it as well. Because variables don't have any effect on rendering
until they're used, they can pass these values through the document
without these kinds of side effects.
The ‘var()’ notation can't be used here
either as it would immediately produce a cycle between $bg and $bg2,
making them both invalid.
When a variable property has its initial value, the variable it defines represents an invalid variable. Using an invalid variable in a property value (including other variable 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: $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.
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.
Variable properties are ordinary properties, and can be read or modified using all of the existing CSSOM APIs for reading or modifying properties.
The specification extends the IDL definitions in the CSSOM spec to
represent the use of the ‘var()’ function.
The CSSVariableComponentValue interface represents a use of the
‘var()’ function.
[NoInterfaceObject] interface CSSVariableComponentValue {
attribute DOMString variableName;
readonly attribute any variableValue;
}
variableName of type DOMString
variableValue of type any, readonly
CSSStyleDeclaration Interface The set of variable properties is open-ended, so it's not
clear how best to represent this. Ideally, the CSSOM would expose the
current set of properties with a non-initial value and allow setting of
arbitrary properties. The most natural way seems to be to first, set up a
getter behavior on the interface somehow that deals with variable
properties, and second, set up a vars map that exposes the
variable properties that aren't set to their initial value.
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 to CSS Variables Module is defined for three conformance classes:
A style sheet is conformant to CSS Variables Module if all of its declarations that use properties defined in this module have values that are valid according to the generic CSS grammar and the individual grammars of each property as given in this module.
A renderer is conformant to CSS Variables Module if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by CSS Variables Module 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 CSS Variables Module 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.
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.
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.
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.
For this specification to be advanced to Proposed Recommendation, there must be at least two independent, interoperable implementations of each feature. Each feature may be implemented by a different set of products, there is no requirement that all features be implemented by a single product. For the purposes of this criterion, we define the following terms:
The specification will remain Candidate Recommendation for at least six months.
Thanks to Daniel Glazman and Dave Hyatt for writing the original Variables draft in 2008. Thanks to many WG members for keeping the idea of variables alive through the years. Thanks to Roland Steiner and Shane Stephens for invaluable feedback and implementation experience.
| Property | Values | Initial | Applies to | Inh. | Percentages | Media |
|---|---|---|---|---|---|---|
| var-* | <value> | (nothing, see prose) | all elements | yes | specified value with variables substituted (but see prose for "invalid variables") | all |