CSS Variables Module Level 1

[LONGSTATUS] [DATE]

This version:
http://dev.w3.org/csswg/css-variables/
Editor's draft:
http://dev.w3.org/csswg/css-variables/
Editors:
Tab Atkins Jr., Google, Inc.

Abstract

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.

Status of this document

Table of contents

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 user-defined properties known collectively as data properties, which allow an author to assign arbitrary values to a property with an author-chosen name, and 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 editting 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.

Module Interactions

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

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 [[CSS3COLOR]], when combined with this module, expands the definition of the <color> value type as used in this specification.

Defining Variables With Data Properties

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

Name: data-*
Values:
Figure this out - restricted or wide-open
Initial: invalid (a keyword, but see prose)
Applies To: all elements
Inherited: yes
Computed Value: specified value with variables substituted
Media: all

Any property name starting with the prefix "data-" is a data property. Spec what values a data property can have. Data 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 data properties or attach a specific effect to them beyond the bare minimum that comes from them being valid properties.

For each data property, there is an associated variable with the same name save for the "data-" prefix. For example, a data property named "data-foo" is associated with the variable named "foo". See the next chapter for details on how to use variables.

This style rule:

:root {
  data-header-color: #06c;
}

declares a data property named "data-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: data(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 ''data(header-color)'' is used elsewhere in the stylesheet, all of the uses can be updated at once by changing the 'data-header-color' property on the root element.

Data 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 data property is declared multiple times, the standard cascade rules help resolve it. Variables always draw from the computed value of the associated data property on the same element:

:root { data-color: blue; }
div { data-color: green; }
#alert { data-color: red; }
* { color: data(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>

Data properties may use variables in their own values to build up composite variables. This can create cyclic dependencies where two or more data properties each attempt to use the variable that the other defines; doing so makes all the data properties involved in the cycle define invalid variables instead of the values they had intended to define.

This example shows a data property safely using a variable:

:root {
	data-main-color: #c06;
	data-accent-background: linear-gradient(to top, data(main-color), white);
}

The 'data-accent-background' property will automatically update when the 'data-main-color' property is changed.

On the other hand, this example shows an invalid instance of variables depending on each other:

:root {
	data-one: calc(data(two) + 20px);
	data-two: calc(data(one) - 20px);
}

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

It is important to note that data 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 data properties on the same element refer to each other; data 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 data properties are not cyclic, and all define valid variables:

<one><two><three /></two></one>
one   { data-foo: 10px; }
two   { data-bar: calc(data(foo) + 10px); }
three { data-foo: calc(data(bar) + 10px); }

The <one> element defines a value for 'data-foo'. The <two> element inherits this value, and additionally assigns a value to 'data-bar'. Finally, the <three> element inherits the 'data-bar' value after variable substitution (in other words, it sees the value ''calc(10px + 10px)''), and then redefines 'data-foo' in terms of that value. Since the value it inherited for 'data-bar' no longer contains a reference to the 'data-foo' property defined on <one>, defining 'data-foo' using the ''data(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 initial value of a data property is a special invalid value which makes the associated variable an invalid variable. This is represented by the keyword ''invalid'', but that keyword has no special meaning in itself, and is valid if set explicitly in a data property.

<div>
  <p>Sample text</p>
</div>
<style>
p { data-foo: invalid; }
div,p { font-family: data(foo); }
</style>

In this example, the "foo" variable is an invalid variable at the time the DIV element references it, because the 'data-foo' property still has its initial value. This causes the DIV's 'font-family' property to compute to the initial value for 'font-family'.

On the other hand, the P element defines an explicit value for the 'data-foo' property. Its 'font-family' property thus references a font named "invalid".

Using Variables

A variable can be used anywhere a value is expected in CSS. 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, 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.

I'm not sure how to precisely define where/how variables can be used. The Grammar section has a perfect definition, if only it weren't all non-normative (because it's just extending the 2.1 grammar). I don't know if 2.1 actually has a term for what is represented by the "term" production in the 2.1 grammar.

Basically, though, variables are lexically substituted into the property value, with restrictions on where they can appear as implied by the Grammar section. You can't, for example, do something ridiculous like ''@var $unit px; div { width: 20$unit; }''.

For example, the following usage is fine from a syntax standpoint, but results in nonsense when the variable is substituted in:

@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.

Using Invalid Variables

An invalid variable results from having variables directly or indirectly refer to themselves, or from using an undefined variable. Using an invalid variable in a property value makes the declaration invalid at computed-value time.

A declaration that is invalid at computed-value time results from either using an invalid variable in a property value, or using a valid variable that produces an invalid declaration when it is substituted in. When this happens, the declaration must compute to the property's initial value.

For example, in the following code:

@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 (such as if it was part of a cycle) or undefined.

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. I think ''attr()'' needs to rely on it as well, as its behavior is almost identical to variables.

APIs

CSS Variables are mutable - one can change them after they've been defined, through the CSSOM. This can be done in two ways: one can read the current variable definition and set an override definition through the convenient .vars property, or manipulate the definitions in the stylesheets directly through the standard CSSOM stylesheet interface.

The Simple API

Not exactly sure how to define this, but I want to put a 'css' property on document (and hopefully window) as a hook for this and other future CSS apis. document.css would then expose a 'vars' property that implements CSSOverrideVariablesMap. Variables are document-global, so they need to be exposed at the document level, not the stylesheet level.

Do I need to define the concept of the override stylesheet? Several browsers already expose this concept of a script-only stylesheet that overrides all other stylesheets.

The CSSOverrideVariablesMap presents a simple interface to the variables in the override stylesheet, which take precedence over variables defined elsewhere in the document. As a convenience, it also allows reading normal variables defined elsewhere in the document, as long as there is no variable with the same name in the override stylesheet.

[NoInterfaceObject] CSSOverrideVariablesMap {
  getter any (DOMString variableName);
  setter void (DOMString variableName, any variableValue);
  creator void (DOMString variableName, any variableValue);
  deleter void (DOMString variableName);
}

On getting, if a variable named variableName exists in the override stylesheet, return its value. Otherwise, if a variable named variableName is defined in the document, return its value. Otherwise, return null.

On setting, find the variable named variableName in the override stylesheet and set its value to variableValue.

On creating, append a new variable rule to the override stylesheet, with the variable name set to variableName and the value set to variableValue.

On deleting, remove the variable with the name variableName from the override stylesheet.

Additions to the Stylesheet Interface

This specification extends the IDL definitions in the CSSOM spec [[!CSSOM]] in several ways.

Changes to interface CSSRule

IDL Definition
interface CSSRule {

  // RuleType
  const unsigned short UNKNOWN_RULE             = 0;
  const unsigned short STYLE_RULE               = 1;
  const unsigned short CHARSET_RULE             = 2;
  const unsigned short IMPORT_RULE              = 3;
  const unsigned short MEDIA_RULE               = 4;
  const unsigned short FONT_FACE_RULE           = 5;
  const unsigned short PAGE_RULE                = 6;
  const unsigned short VARIABLE_RULE            = 11;
  readonly attribute unsigned short	type;
           attribute DOMString		cssText;
                                          // raises(DOMException) on setting
  readonly attribute CSSStyleSheet	parentStyleSheet;
  readonly attribute CSSRule		parentRule;
};
Defined Constants
VARIABLE_RULE: The rule is a CSSVariableRule.

Going with value 11 for now, since CSSOM seems to reserve 0-10.

Interface CSSVariableRule

The CSSVariableRule interface represents a ''@var'' rule within a CSS stylesheet. The ''@var'' rule is used to define variables.

IDL Definition
interface CSSVariableRule : CSSRule {
  attribute DOMString name;
  attribute DOMString value;
}

Interface CSSVariableComponentValue

The CSSVariableComponentValue interface represents a call to a CSS Variable.

IDL Definition
[NoInterfaceObject] interface CSSVariableComponentValue {
           attribute DOMString variableName;
  readonly attribute any variableValue;
}
Attributes
variableName of type DOMString
This attribute is used for the name of the variable. Changing this attribute changes the variable being referred to.
variableValue of type any, readonly
This attribute is used for the value of the variable.

The Grammar of Variables

I'm not sure if I've done this section correctly. For now, I'll try my best to copypasta what Conditionals is doing, since dbaron usually know what's what.

This specification extends the lexical scanner in the Grammar of CSS 2.1 ([CSS21], Appendix G) by adding:

@{V}{A}{R}    {return VARIABLE_SYM;}
"$"name       {return VARIABLE;}

and the grammar by adding:

variable_rule
  : VARIABLE_SYM S+ variable_name S+ expr ':';
  ;

and by amending:

stylesheet
  : [ CHARSET_SYM STRING ';' ]?
    [S|CDO|CDC]* [ import [ CDO S* | CDC S* ]* ]*
    [ [ ruleset | media | page | variable_rule ] [ CDO S* | CDC S* ]* ]*
  ;
nested_statement
  : ruleset | media | page | font_face_rule | keyframes-rule |
    supports_rule | document_rule | variable_rule
  ;
term
  : unary_operator?
    [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
      TIME S* | FREQ S* ]
  | STRING S* | IDENT S* | URI S* | hexcolor | function | VARIABLE S*
  ;

This uses the 'nested_statement' production from Conditionals. That should make its way to a proper draft, like a new release of Syntax.

Should variables be usable elsewhere, like in the value of a MQ?

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 CSS Variables Module 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 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.

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.

CR Exit Criteria

[Change or remove the following CR exit criteria if the spec is not a module, but, e.g., a Note or a profile. This text was decided on 2008-06-04.]

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:

independent
each implementation must be developed by a different party and cannot share, reuse, or derive from code used by another qualifying implementation. Sections of code that have no bearing on the implementation of this specification are exempt from this requirement.
interoperable
passing the respective test case(s) in the official CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.
implementation
a user agent which:
  1. implements the specification.
  2. is available to the general public. The implementation may be a shipping product or other publicly available version (i.e., beta version, preview release, or “nightly build”). Non-shipping product releases must have implemented the feature(s) for a period of at least one month in order to demonstrate stability.
  3. is not experimental (i.e., a version specifically designed to pass the test suite and is not intended for normal usage going forward).

The specification will remain Candidate Recommendation for at least six months.

Acknowledgments

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.

References

Normative references

Other references

Index

Property index