Skip to content

Instantly share code, notes, and snippets.

@tabatkins
Created February 14, 2013 01:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tabatkins/4950013 to your computer and use it in GitHub Desktop.
Save tabatkins/4950013 to your computer and use it in GitHub Desktop.
What it might look like to write the Variables spec in Markdown, with a few obvious extension points for a custom processor to fill in.
CSS Custom Properties for Cascading Variables Module Level 1
============================================================
~~~~metadata
Status: ED
TR draft: http://www.w3.org/TR/css-variables/
Editor's draft: http://dev.w3.org/csswg/css-variables/
Editor: Tab Atkins Jr. (Google, Inc.) http://xanthir.com/contact
Editor: Luke Macpherson (Google, Inc.) macpherson@google.com
Editor: Daniel Glazman (Disruptive Innovations) daniel.glazman@disruptive-innovations.com
~~~~
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.
Introduction
------------{#intro}
*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.
### Module Interactions ### {#placement}
This module defines a new type of primitive value,
the [variable],
which is accepted by all properties.
### Values ### {#values}
This specification follows the [CSS property definition conventions](http://www.w3.org/TR/CSS21/about.html#property-defs) 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 Custom Properties: the 'var-*' family of properties
------------------------------------------------------------{#defining-variables}
This specification defines an open-ended set of properties called [custom properties],
which are used to define [variables].
~~~~propdef
Name: var-*
Values: [ <var>&lt;value></var> | <var>&lt;CDO></var> | <var>&lt;CDC></var> ]
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
~~~~
A <dfn title="custom property|custom properties">custom property</dfn> is any property
whose name is composed of "var-" followed by an `&lt;ident>` [[!CSS3VAL]]
[Custom properties] are solely for use by authors and users;
CSS will never give them a meaning beyond what is presented here.
Unlike other CSS properties,
custom properties are **case-sensitive**.
The "var-" prefix **must** be written in lower-case.
<example>
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.
</example>
[Custom properties] have an extremely permissive value grammar.
The <dfn>&lt;value></dfn> in its grammar corresponds to the "value" production
in [CSS 2.1 Chapter 4.1](http://www.w3.org/TR/CSS2/syndata.html#tokenization) [[!CSS21]],
while <dfn>&lt;CDO></dfn> and <dfn>&lt;CDC></dfn> correspond to the tokens of the same name
from the same chapter
(they represent HTML comments showing up in CSS text - "&lt;!--" and "").
This is a very technical way of saying that nearly anything can be used in the value of a custom property,
save unmatched closing brackets ("]", ")", or "}"),
a top-level semicolon (as it will end the property),
a "!important" that's not at the end,
or invalid tokens (such as BAD_STRING and BAD_URL).
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.
<example>
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.
</example>
There are an infinity of [custom properties],
but the initial value of a [custom property] is an empty invalid value.
This means that,
until a [custom property] is explicitly defined otherwise by a style sheet,
it defines an [invalid variable].
The primary purpose of [custom properties] is to define [cascading variables].
In CSS, a <dfn title="variable|cascading variable">cascading variable</dfn> 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.
<example>
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.
</example>
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..
<example>
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); }
&lt;p>I inherited blue from the root element!&lt;/p>
&lt;div>I got green set directly on me!&lt;/div>
&lt;div id='alert'>
While I got red set directly on me!
&lt;p>I'm red too, because of inheritance!&lt;/p>
&lt;/div>
~~~~
</example>
[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).
<example>
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.
</example>
<example> {.invalid-example}
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.
</example>
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.
<example>
For example,
given the following structure,
these custom properties are **not** cyclic,
and all define valid variables:
~~~~
&lt;one>&lt;two>&lt;three />&lt;/two>&lt;/one>
one { var-foo: 10px; }
two { var-bar: calc(var(foo) + 10px); }
three { var-foo: calc(var(bar) + 10px); }
~~~~
The &lt;one> element defines a value for 'var-foo'.
The &lt;two> element inherits this value,
and additionally assigns a value to 'var-bar' using the ''foo'' variable.
Finally,
the &lt;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 &lt;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''.
</example>
<!--
UUUUUUUU UUUUUUUU iiii
U::::::U U::::::U i::::i
U::::::U U::::::U iiii
UU:::::U U:::::UU
U:::::U U:::::U ssssssssss iiiiiiinnnn nnnnnnnn ggggggggg ggggg
U:::::D D:::::U ss::::::::::s i:::::in:::nn::::::::nn g:::::::::ggg::::g
U:::::D D:::::Uss:::::::::::::s i::::in::::::::::::::nn g:::::::::::::::::g
U:::::D D:::::Us::::::ssss:::::s i::::inn:::::::::::::::ng::::::ggggg::::::gg
U:::::D D:::::U s:::::s ssssss i::::i n:::::nnnn:::::ng:::::g g:::::g
U:::::D D:::::U s::::::s i::::i n::::n n::::ng:::::g g:::::g
U:::::D D:::::U s::::::s i::::i n::::n n::::ng:::::g g:::::g
U::::::U U::::::Ussssss s:::::s i::::i n::::n n::::ng::::::g g:::::g
U:::::::UUU:::::::Us:::::ssss::::::si::::::i n::::n n::::ng:::::::ggggg:::::g
UU:::::::::::::UU s::::::::::::::s i::::::i n::::n n::::n g::::::::::::::::g
UU:::::::::UU s:::::::::::ss i::::::i n::::n n::::n gg::::::::::::::g
UUUUUUUUU sssssssssss iiiiiiii nnnnnn nnnnnn gggggggg::::::g
g:::::g
gggggg g:::::g
g:::::gg gg:::::g
g::::::ggg:::::::g
gg:::::::::::::g
ggg::::::ggg
gggggg
-->
<h2 id='using-variables'>
Using Cascading Variables: the ''var()'' notation</h2>
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:
~~~~
<dfn id='default-var-type'>&lt;variable></dfn> = var( <var>variable-name</var> [, <var>&lt;fallback></var> ]? )
~~~~
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 <var>&lt;fallback></var> value is identical to the syntax of a [custom property].
If the variable named by the first argument is valid,
the variable's value is substituted as normal.
If it's invalid, and a <var>&lt;fallback></var> was provided,
the <var>&lt;fallback></var> is substituted instead.
Otherwise, the variable is an [invalid variable].
<example>
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);
}
~~~~
</example>
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].
<example>
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.
</example>
In 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.
### Invalid Variables ### {#invalid-variables}
When a [custom property] has its initial value,
the [variable] it defines
represents an <dfn>invalid variable</dfn>.
Using an [invalid variable] in a property value
(including other [custom properties])
makes the declaration [invalid at computed-value time].
A declaration can be <dfn>invalid at computed-value time</dfn>
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.
<example>
For example, in the following code:
~~~~
:root { var-not-a-color: 20px; }
p { background-color: red; }
p { background-color: var(not-a-color); }
~~~~
the &lt;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.
</example>
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.
<!--
AAA PPPPPPPPPPPPPPPPP IIIIIIIIII
A:::A P::::::::::::::::P I::::::::I
A:::::A P::::::PPPPPP:::::P I::::::::I
A:::::::A PP:::::P P:::::PII::::::II
A:::::::::A P::::P P:::::P I::::I
A:::::A:::::A P::::P P:::::P I::::I
A:::::A A:::::A P::::PPPPPP:::::P I::::I
A:::::A A:::::A P:::::::::::::PP I::::I
A:::::A A:::::A P::::PPPPPPPPP I::::I
A:::::AAAAAAAAA:::::A P::::P I::::I
A:::::::::::::::::::::A P::::P I::::I
A:::::AAAAAAAAAAAAA:::::A P::::P I::::I
A:::::A A:::::A PP::::::PP II::::::II
A:::::A A:::::A P::::::::P I::::::::I
A:::::A A:::::A P::::::::P I::::::::I
AAAAAAA AAAAAAAPPPPPPPPPP IIIIIIIIII
-->
APIs
----{#cssom}
### Extensions to the `CSSStyleDeclaration` Interface ### {#the-cssstyledeclaration-interface}
The <dfn>`CSSStyleDeclaration`</dfn> interface is amended as follows:
~~~~idl
partial interface CSSStyleDeclaration {
attribute CSSVariablesDeclaration var;
}
~~~~
#### Serializing Custom Properties #### {#serializing-custom-props}
Custom property names must be serialized exactly as provided by the author.
### The `CSSVariablesDeclaration` Interface ### {#the-cssvariablesdeclaration-interface}
The <dfn>`CSSVariablesDeclaration`</dfn> interface exposes the [custom properties] declared in the parent declaration block,
in a more convenient fashion than the `getPropertyValue()`/etc. functions.
~~~~idl
interface CSSVariablesDeclaration {
[getter] DOMString (DOMString varName);
[setter] [creator] void (DOMString varName, DOMString varValue);
[deleter] void (DOMString varName);
}
~~~~
The [supported property names](http://dev.w3.org/2006/webapi/WebIDL/#dfn-supported-property-names)
on a CSSStyleDeclaration object
are the property names of all the [custom properties] in the [<dfn>CSS declaration block declarations</dfn>](http://dev.w3.org/csswg/cssom/#css-declaration-block-declarations),
with the "var-" prefix removed.
Before running any of the algorithms in this section,
prepend "var-" to <var>varName</var>&apos;s value.
When asked to <dfn id='cssvariablesdeclaration-getter' title='getter'>get the value of a variable</dfn>,
if <var>varName</var> is in the [CSS declaration block declarations],
invoke `getPropertyValue()` by passing <var>varName</var> as its argument,
and return the returned value.
Otherwise, return the empty string.
When asked to <dfn id='cssvariablesdeclaration-setter' title='setter'>set</dfn> or <dfn id='cssvariablesdeclaration-creator' title='creator'>create the value of a variable</dfn>,
if <var>varName</var> matches the grammar of a [custom property] name:
if <var>varValue</var> is the empty string,
invoke <i title='deleter'>the algorithm to delete a variable];
otherwise, invoke `setProperty()` by passing <var>varName</var> as the <var>property</var> argument and <var>varValue</var> as the <var>value</var> argument.
When asked to <dfn id='cssvariablesdeclaration-deleter' title='deleter'>delete the value of a variable</dfn>,
if <var>varName</var> matches the grammar of a [custom property] name,
invoke `removeProperty()` by passing <var>varName</var> as its argument,
and return the returned value.
Otherwise, do nothing and return the empty string.
Acknowledgments
---------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment