</
The <one> element defines a value for --foo. The <two> element inherits this value, and additionally assigns a value to --bar using the foo variable. Finally, the <three> element inherits the --bar value after variable substitution (in other words, it sees the value calc(10px + 10px)), and then redefines --foo in terms of that value. Since the value it inherited for --bar no longer contains a reference to the --foo property defined on <one>, defining --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.
The value of a custom property can be substituted into the value of another property with the var() function. The syntax of var() is:
var () =var ( <custom-property-name>, <declaration-value>?)
@supports
In an exception to the usual comma elision rules, which require commas to be omitted when they’re not separating values, a bare comma, with nothing following it, must be treated as valid in var(), indicating an empty fallback value.
Note: That is, var(--a,) is a valid function, specifying that if the --a custom property is invalid or missing, the var() should be replaced with nothing.
The var() function can be used in place of any part of a value in any property on an element. The var() function 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.)
.foo{ --side : margin-top; var ( --side) :20 px ; }
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.
The first argument to the function is the name of the custom property to be substituted. The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the value of the referenced custom property is the guaranteed-invalid value.
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.
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{ --text-color : #080; /* header-color isn’t set, and so remains blue, the fallback value */ }
If a property contains one or more var() functions, and those functions are syntactically valid, the entire property’s grammar must be assumed to be valid at parse time. It is only syntax-checked at computed-value time, after var() functions have been substituted.
To substitute a var() in a property’s value:
Note: Other things can also make a property invalid at computed-value time.
CSSOM
.foo{ --gap : 20 ; margin-top : var ( --gap) px; }
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{ --gap : 20 ; margin-top : calc ( var ( --gap) *1 px ); }
var() functions are substituted at computed-value time. If a declaration, once all var() functions are substituted in, does not match its declared grammar, the declaration is invalid at computed-value time.
If a declaration, once all var() functions are substituted in, contains only a CSS-wide keyword (and possibly whitespace), its value is determined as if that keyword were its specified value all along.
:root{ --looks-valid : 20 px ; } 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.
p{ color : var ( --does-not-exist, initial); }
In the above code, if the --does-not-exist property didn’t exist or is invalid at computed-value time, the var() will instead substitute in the initial keyword, making the property behave as if it was originally color: initial. This will make it take on the document’s initial color value, rather than defaulting to inheritance, as it would if there were no fallback.
When a custom property’s value is the guaranteed-invalid value, var() functions cannot use it for substitution. Attempting to do so makes the declaration invalid at computed-value time, unless a valid fallback is specified.
A declaration can be invalid at computed-value time if it contains a var() that references a custom property with the guaranteed-invalid value, as explained above, or if it uses a valid custom property, but the property value, after substituting its var() functions, is invalid. When this happens, the computed value is one of the following depending on the property’s type:
The computed value is the guaranteed-invalid value.
Either the property’s inherited value or its initial value depending on whether the property is inherited or not, respectively, as if the property’s value had been specified as the unset keyword.
:root{ --not-a-color : 20 px ; } 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 custom property itself was unset, or contained an invalid var() function.
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.
var() functions produce some complications when parsing shorthand properties into their component longhands, and when serializing shorthand properties from their component longhands.
If a shorthand property contains a var() function in its value, the longhand properties it’s associated with must instead be filled in with a special, unobservable-to-authors pending-substitution value that indicates the shorthand contains a variable, and thus the longhand’s value can’t be determined until variables are substituted.
This value must then be cascaded as normal, and at computed-value time, after var() functions are finally substituted in, the shorthand must be parsed and the longhands must be given their appropriate values at that point.
Note: When a shorthand is written without a var(), it is parsed and separated out into its component longhand properties at parse time; the longhands then participate in the cascade, with the shorthand property more or less discarded. When the shorthand contains a var(), however, this can’t be done, as the var() could be substituted with anything.
Pending-substitution values must be serialized as the empty string, if an API allows them to be observed.
Shorthand properties are serialized by gathering the values of their component longhand properties, and synthesizing a value that will parse into the same set of values.
If all of the component longhand properties for a given shorthand are pending-substitution values from the same original shorthand value, the shorthand property must serialize to that original (var()-containing) value.
Otherwise, if any of the component longhand properties for a given shorthand are pending-substitution values, or contain var() functions of their own that have not yet been substituted, the shorthand property must serialize to the empty string.
Naively implemented, var() functions can be used in a variation of the "billion laughs attack":
.foo { --prop1 : lol; --prop2 : var ( --prop1) var ( --prop1); --prop3 : var ( --prop2) var ( --prop2); --prop4 : var ( --prop3) var ( --prop3); /* etc */ }
In this short example, --prop4’s computed value is lol lol lol lol lol lol lol lol, containing 8 copies of the original lol. Every additional level added to this doubles the number of identifiers; extending it to a mere 30 levels, the work of a few minutes by hand, would make --prop30 contain nearly a billion instances of the identifier.
To avoid this sort of attack, UAs must impose a UA-defined limit on the allowed length of the token stream that a var() function expands into. If a var() would expand into a longer token stream than this limit, it instead makes the property it’s expanding into invalid at computed-value time.
This specification does not define what size limit should be imposed. However, since there are valid use-cases for custom properties that contain a kilobyte or more of text, it’s recommended that the limit be set relatively high.
Note: The general principle that UAs are allowed to violate standards due to resource constraints is still generally true here; a UA might, separately, have limits on how long of a custom property they can support, or how large of an identifier they can support. This section calls out this attack specifically because of its long history, and the fact that it can be done without any of the pieces seeming to be too large on first inspection.
All custom property declarations have the case-sensitive flag set.
Note: Custom properties do not appear on a CSSStyleDeclaration object in camel-cased form, because their names may have both upper and lower case letters which indicate distinct custom properties. The sort of text transformation that automatic camel-casing performs is incompatible with this. They can still be accessed by their proper name via getPropertyValue()/etc.
Custom property names must be serialized as the exact code point sequence provided by the author, including not altering the case.
Note: For non-custom properties, property names are restricted to the ASCII range and are ASCII case-insensitive, so implementations typically serialize the name lowercased.
Specified values of custom properties must be serialized exactly as specified by the author. Simplifications that might occur in other properties, such as dropping comments, normalizing whitespace, reserializing numeric tokens from their value, etc., must not occur.
Computed values of custom properties must similarly be serialized exactly as specified by the author, save for the replacement of any var() functions.
--y : /* baz */ ; --x : /* foo */ var ( --y) /* bar */ ;
the serialization of the specified value of --x must be
, while the serialization of the computed value of --x must be
.
(Note that the leading whitespace on the value is automatically trimmed by the CSS parser; it’s not preserved here.)
For example, storing a UUID in a custom property, like --uuid: 12345678-12e3-8d9b-a456-426614174000, requires the UUID to be echoed back out as written when it’s accessed by script.
This value is technically parsed by CSS as a series of adjacent numbers and dimensions. In particular, the segment "-12e3" parses as a number, equal to -12000. Reserializing it in that form, as required by CSSOM in other contexts, would fatally break the author’s use of the value.
Clarified that custom properties apply all pseudo-elements (including those with restricted property lists)
Added example to illustrate issues with combining characters, ligatures, etc
Strengthened wording around similar-appearing variable names that use distinct codepoint sequences
Clarified an example by using more visualy distinct languages as examples (English and Greek)
Split Security and Privacy into separate sections
Now that [css-syntax-3] auto-trims whitespace from declaration values, made <declaration-value> optional in the custom property grammar, so that empty variables are still allowed. (Issue 774)
Similarly, made empty fallbacks valid in var().
The '-' property is reserved for future use by CSS.
Added concept of "animation-tainted", to prevent non-animatable properties from using a variable to smuggle in some animatability.
Defined the guaranteed-invalid value to make the initial value of custom properties and the result of cycles or substitution failure more straightforward, and allow failure to propagate thru substitutions until finally intercepted by a fallback.
Defined that cycles trigger invalid at computed-value time behavior.
Allowed variables to resolve to a CSS-wide keyword (only possible by providing it as a fallback).
Clarified that registered custom properties act like non-custom properties when they’re invalid at computed-value time.
Made longhands with var()s also trigger their shorthands to be unserializable, like longhands with pending-substitution values already did.
Required UAs to defend against exponential substitution attacks.
Defined how to serialize the values of custom properties (previously, only the property name’s serialization was specified).
Serialization of longhands when shorthand uses a variable was defined.
Link to DOM’s definition of "case-sensitive".
Added example of using variables with :lang() to do simple i18n.
Clarified that usage of var() in a custom property must be valid per the var() grammar.
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.
This specification defines a purely author-level mechanism for passing styling information around within a page they control. As such, there are no new privacy considerations.
§ 3.3 Safely Handling Overly-Long Variables calls out a long-standing Denial-of-Service attack that can be mounted against "macro-expansion"-like mechanisms, such as the var() function, and mandates a defense against that attack.
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=
, like this:
Informative notes begin with the word “Note” and are set apart from the normative text with class=
, like this:
Note, this is an informative note.
Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class=
, like this: UAs MUST provide an accessible alternative.
Tests relating to the content of this specification may be documented in “Tests” blocks like this one. Any such block is non-normative.
Conformance to this specification is defined for three conformance classes:
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.
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 stable CSS features, the CSSWG recommends following best practices for the implementation of unstable features and proprietary extensions to CSS.
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.
Name | Value | Initial | Applies to | Inh. | %ages | Animation type | Canonical order | Computed value |
---|---|---|---|---|---|---|---|---|
--* | <declaration-value>? | the guaranteed-invalid value | all elements and all pseudo-elements (including those with restricted property lists) | yes | n/a | discrete | per grammar | specified value with variables substituted, or the guaranteed-invalid value |