CSS Properties and Values API Level 1

W3C Working Draft,

This version:
https://www.w3.org/TR/2017/WD-css-properties-values-api-1-20171109/
Latest published version:
https://www.w3.org/TR/css-properties-values-api-1/
Editor's Draft:
https://drafts.css-houdini.org/css-properties-values-api-1/
Previous Versions:
Feedback:
public-houdini@w3.org with subject line “[css-properties-values-api] … message topic …” (archives)
Issue Tracking:
GitHub
Inline In Spec
Editors:
Tab Atkins-Bittner (Google)

Abstract

This CSS module defines an API for registering new CSS properties. Properties registered using this API are provided with a parse syntax that defines a type, inheritance behaviour, and an initial value.

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 https://www.w3.org/TR/.

Publication as a 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.

GitHub Issues are preferred for discussion of this specification. When filing an issue, please put the text “css-properties-values-api” in the title, preferably like this: “[css-properties-values-api] …summary of comment…”. All issues and comments are archived.

This document was published by the CSS Working Group and the Technical Architecture Group.

This document was produced by groups operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures (CSS) and a public list of any patent disclosures (Technical Architecture Group) made in connection with the deliverables of each group; these pages also include 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 document is governed by the 1 March 2017 W3C Process Document.

1. Introduction

CSS defines a comprehensive set of properties that can be manipulated in order to modify the layout, paint, or behaviour of a web document. However, web authors frequently wish to extend this set with additional properties.

[css-variables] provides primitive means for defining user-controlled properties, however these properties always take token lists as values, must always inherit, and can only impact document layout or paint by being re-incorporated into the value of other properties via a var() reference.

This specification extends [css-variables], allowing the registration of properties that have a value type, an initial value, and a defined inheritance behaviour.

This specification is complementary to [css-paint-api] and [css-layout-api], which allow custom properties to directly impact paint and layout behaviours respectively.

2. Registering custom properties

dictionary PropertyDescriptor {
    required DOMString name;
             DOMString syntax       = "*";
             boolean   inherits     = false;
             DOMString initialValue;
};


partial interface CSS {
    static void registerProperty(PropertyDescriptor descriptor);
    static void unregisterProperty(DOMString name);
};

Additional, the Document object gains a new [[registeredPropertySet]] private slot, which is a set of records that describe registered custom properties.

2.1. The PropertyDescriptor dictionary

A PropertyDescriptor dictionary represents author-specified configuration options for a custom property. PropertyDescriptor dictionaries contain the following members:

name, of type DOMString

The name of the custom property being defined.

syntax, of type DOMString, defaulting to "*"

A string representing how this custom property is parsed.

inherits, of type boolean, defaulting to false

True if this custom property should inherit down the DOM tree; False otherwise.

initialValue, of type DOMString

The initial value of this custom property.

2.2. The registerProperty() and unregisterProperty() functions

The registerProperty(PropertyDescriptor descriptor) method registers a custom property according to the configuration options provided in descriptor. When it is called, it executes the register a custom property algorithm, passing the options in its descriptor argument as arguments of the same names.

To register a custom property with name being a string, and optionally syntax being a string, inherits being a boolean, and initialValue being a string, execute these steps:
  1. Let property set be the value of the current global object’s associated Document’s [[registeredPropertySet]] slot.

  2. Attempt to parse name as a <custom-property-name>. If this fails, throw a SyntaxError and exit this algorithm.

    Otherwise, let parsed name be the parsed value.

    If property set already contains an entry with parsed name as its property name (compared codepoint-wise), throw an InvalidModificationError and exit this algorithm.

  3. If syntax is not present, or is equal to "*" (U+002A ASTERISK), let parsed syntax be undefined, and skip to the next step of this algorithm.

    Otherwise, attempt to parse syntax according to the rules in §2.3 Supported syntax strings. If it does not parse successfully, throw a SyntaxError. Otherwise, let parsed syntax be the parsed syntax.

    Note: For example, a valid syntax string is something like "<length>", or "<number>+"; the allowed syntax is a subset of CSS Values 3 §2 Value Definition Syntax. Future levels of this specification are expected to expand the complexity of allowed syntax strings, allowing custom properties that more closely resemble the full breadth of what CSS properties allow.

  4. If parsed syntax is undefined, and initialValue is not present, let parsed initial value be empty. This must be treated identically to the "default" initial value of custom properties, as defined in [css-variables]. Skip to the next step of this algorithm.

    Otherwise, if parsed syntax is undefined, parse initialValue as a <declaration-value>. If this fails, throw a SyntaxError and exit this algorithm. Otherwise, let parsed initial value be the parsed result. Skip to the next step of this algorithm.

    Otherwise, if initialValue is not present, throw a SyntaxError and exit this algorithm.

    Otherwise, parse initialValue according to parsed syntax. If this fails, throw a SyntaxError and exit this algorithm.

    Otherwise, let parsed initial value be the parsed result. If parsed initial value is not computationally independent, throw a SyntaxError and exit this algorithm.

  5. If inherits is present, set inherit flag to its value. Otherwise, set inherit flag to false.

  6. Let registered property be a record with a property name of parsed name, a syntax of parsed syntax, an initial value of parsed initial value, and an inherit flag of inherit flag. Add registered property to property set.

A property value is computationally independent if it can be converted into a computed value using only the value of the property on the element, and "global" information that cannot be changed by CSS.

For example, 5px is computationally independent, as converting it into a computed value doesn’t change it at all. Similarly, 1in is computationally independent, as converting it into a computed value relies only on the "global knowledge" that 1in is 96px, which can’t be altered or adjusted by anything in CSS.

On the other hand, 3em is not computationally independent, because it relies on the value of font-size on the element (or the element’s parent). Neither is a value with a var() function, because it relies on the value of a custom property.

When a custom property is registered with a given type, the process via which specified values for that property are turned into computed values is defined fully by the type selected, as described in §2.4 Calculation of Computed Values.

Properties can be unregistered using unregisterProperty(DOMString name). When it is called, it executes the unregister a custom property algorithm, with a name set to its sole argument.

To unregister a custom property with the name name:
  1. Let property set be the value of the current global object’s associated Document’s [[registeredPropertySet]] slot.

  2. Attempt to parse name as a <custom-property-name>. If this fails, throw a SyntaxError and exit this algorithm.

    Otherwise, let parsed name be the parsed value.

  3. If property set contains a record with a property name matching parsed name (compared codepoint-wise), remove the record from property set.

    Otherwise, throw a NotFoundError.

When the current global object’s associated Document’s [[registeredPropertySet]] changes, previously syntactically invalid property values can become valid and vice versa. This can change the set of declared values which requires the cascade to be recomputed.

By default, all custom property declarations that can be parsed as a sequence of tokens are valid. Hence, the result of this stylesheet:
.thing {
    --my-color: green;
    --my-color: url("not-a-color");
    color: var(--my-color);
}

is to set the color property of elements of class "thing" to inherit. The second --my-color declaration overrides the first at parse time (both are valid), and the var() reference in the color property is found to be invalid at computed-value time (because url("not-a-color") is not a color). At this stage of the CSS pipeline (computation time), the only available fallback is the initial value of the property, which in the case of color is inherit. Although there was a valid usable value (green), this was removed during parsing because it was superseded by the URL.

If we call:

CSS.registerProperty({
    name: "--my-color",
    syntax: "<color>",
    initialValue: "black"
});

then the second --my-color declaration becomes syntactically invalid at parse time, and is ignored. The first --my-color is the only valid declaration left for the property, so color is set to the value green.

2.3. Supported syntax strings

The following syntax strings are supported:

"<length>"

Any valid <length> value

"<number>"

<number> values

"<percentage>"

Any valid <percentage> value

"<length-percentage>"

Any valid <length> or <percentage> value, any valid <calc()> expression combining <length> and <percentage> components.

"<color>"

Any valid <color> value

"<image>"

Any valid <image> value

"<url>"

Any valid <url> value

"<integer>"

Any valid <integer> value

"<angle>"

Any valid <angle> value

"<time>"

Any valid <time> value

"<resolution>"

Any valid <resolution> value

"<transform-list>"

A list of valid <transform-function> values

"<custom-ident>"

Any valid <custom-ident> value

Any sequence consisting of a name-start code point, followed by zero or more name code points, which matches the <custom-ident> production

That identifier

Note: <custom-ident>s are compared codepoint-wise with each other; this is different than the normal behavior of UA-defined CSS which limits itself to ASCII and is ASCII case-insensitive. So, specifying an ident like Red means that the precise value Red is accepted; red, RED, and any other casing variants are not matched by this. It is recommended that idents be restricted to ASCII and written in lower-case, to match CSS conventions.

One of the preceding strings, followed by '+'

A space-separated list of one or more repetitions of the type specified by the string. Note: Since <transform-list> is already a space separated list, <transform-list>+ is invalid.

Any combination of the preceding, separated by '|'

Any value that matches one of the items in the combination, matched in specified order.

Note: That is, given the syntax string "red | <color>", matching the value red against it will parse as an identifier, while matching the value blue will parse as a <color>.

"*"

Any valid token stream

Note: [css3-values] maintains a distinction between properties that accept only a length, and properties that accept both a length and a percentage, however the distinction doesn’t currently cleanly line up with the productions. Accordingly, this specification introduces the length-percentage production for the purpose of cleanly specifying this distinction.

Regardless of the syntax specified, all custom properties will accept CSS-wide keywords as well as revert, and process these values appropriately.

Note: This does not apply to the initialValue member of the PropertyDescriptor dictionary.

For example, the following are all valid syntax strings.
"<length>"

accepts length values

"<length> | <percentage>"

accepts lengths, percentages, percentage calc expressions, and length calc expressions, but not calc expressions containing a combination of length and percentage values.

"<length-percentage>"

accepts all values that "<length> | <percentage>" would accept, as well as calc expressions containing a combination of both length and percentage values.

"big | bigger | BIGGER"

accepts the ident "big", or the ident "bigger", or the ident "BIGGER".

"<length>+"

accepts a list of length values.

2.4. Calculation of Computed Values

The syntax of a custom property fully determines how computed values are generated from specified values for that property.

The CSS-wide keywords and revert generate computed values as described in [css3-values] and [css-cascade-4] respectively. Otherwise:

For <length> values, the computed value is the absolute length expressed in pixels.

For <length-percentage> values, the computed value is one of the following:

For <custom-ident>, ident, <color>, <image>, <url>, <integer>, <angle>, <time>, <resolution> or "*" values, the computed value is as specified.

For <number> and <percentage> values which are not calc expressions, the computed value is as specified. Calc expressions that are <number> and <percentage> values get reduced during computation to simple numbers and percentages respectively.

For <transform-function> values contained in <transform-list> values, the computed value is as specified but with all lengths resolved to their computed values.

For values specified by a syntax string that include "|" clauses, the computed value is given by applying the calculation rules for the first clause that matches to the specified value.

For list values, the computed value is a list of the computed values of the primitives in the list.

3. Behavior of Custom Properties

3.1. Animation Behavior of Custom Properties

Note: As defined by [css3-animations] and [css3-transitions], it is possible to specify animations and transitions that reference custom properties.

When referenced by animations and transitions, custom properties interpolate in a manner defined by their types. If their type is defined as a list with "+", it’s interpolated as a simple list [css3-transitions].

If the start and end of an interpolation have matching types, then they will interpolate as specified in [css3-animations]. Otherwise, the interpolation falls back to the default 50% flip described in [css3-animations].

Intermediate interpolated results of animations on custom properties must be able to generate a token stream representing their value. We should ensure that this is standard across implementations to avoid interop issues.

3.2. Conditional Rules

@supports rules and the supports(conditionText) method behave as specified in [css-variables].

Note: In other words, for the purpose of determining whether a value is supported by a given custom property, the type registered for the custom property is ignored and any value consisting of at least one token is considered valid.

should @supports pay attention to type when considering custom properties? <https://github.com/w3c/css-houdini-drafts/issues/118>

4. Examples

4.1. Example 1: Using custom properties to add animation behavior

<script>
CSS.registerProperty({
    name: "--stop-color",
    syntax: "<color>",
    inherits: false,
    initialValue: "rgba(0,0,0,0)"
});
</script>


<style>


.button {
    --stop-color: red;
    background: linear-gradient(var(--stop-color), black);
    transition: --stop-color 1s;
}


.button:hover {
    --stop-color: green;
}


</style>

5. Security Considerations

There are no known security issues introduced by these features.

6. Privacy Considerations

There are no known privacy issues introduced by these features.

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.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with <strong class="advisement">, like this: UAs MUST provide an accessible alternative.

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.

Implementations of Unstable and Proprietary Features

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.

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 https://www.w3.org/Style/CSS/Test/. Questions should be directed to the public-css-testsuite@w3.org mailing list.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-CASCADE-4]
Elika Etemad; Tab Atkins Jr.. CSS Cascading and Inheritance Level 4. 14 January 2016. CR. URL: https://www.w3.org/TR/css-cascade-4/
[CSS-CONDITIONAL-3]
CSS Conditional Rules Module Level 3 URL: https://www.w3.org/TR/css3-conditional/
[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. 20 February 2014. CR. URL: https://www.w3.org/TR/css-syntax-3/
[CSS-TRANSFORMS-1]
Simon Fraser; et al. CSS Transforms Module Level 1. 26 November 2013. WD. URL: https://www.w3.org/TR/css-transforms-1/
[CSS-VARIABLES]
Tab Atkins Jr.. CSS Custom Properties for Cascading Variables Module Level 1. 3 December 2015. CR. URL: https://www.w3.org/TR/css-variables-1/
[CSS3-ANIMATIONS]
Dean Jackson; et al. CSS Animations. 19 February 2013. WD. URL: https://www.w3.org/TR/css3-animations/
[CSS3-COLOR]
Tantek Çelik; Chris Lilley; David Baron. CSS Color Module Level 3. 7 June 2011. REC. URL: https://www.w3.org/TR/css3-color
[CSS3-IMAGES]
Elika Etemad; Tab Atkins Jr.. CSS Image Values and Replaced Content Module Level 3. 17 April 2012. CR. URL: https://www.w3.org/TR/css3-images/
[CSS3-TRANSITIONS]
Dean Jackson; et al. CSS Transitions. 19 November 2013. WD. URL: https://www.w3.org/TR/css3-transitions/
[CSS3-VALUES]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 3. 29 September 2016. CR. URL: https://www.w3.org/TR/css-values-3/
[CSSOM-1]
Simon Pieters; Glenn Adams. CSS Object Model (CSSOM). 17 March 2016. WD. URL: https://www.w3.org/TR/cssom-1/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WebIDL]
Cameron McCormack; Boris Zbarsky; Tobie Langel. Web IDL. 15 December 2016. ED. URL: https://heycam.github.io/webidl/

Informative References

[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley. CSS Color Module Level 4. 5 July 2016. WD. URL: https://www.w3.org/TR/css-color-4/
[CSS-FONTS-3]
John Daggett. CSS Fonts Module Level 3. 3 October 2013. CR. URL: https://www.w3.org/TR/css-fonts-3/
[CSS-LAYOUT-API]
CSS Layout API.
[CSS-PAINT-API]
CSS Painting API.
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/

IDL Index

dictionary PropertyDescriptor {
    required DOMString name;
             DOMString syntax       = "*";
             boolean   inherits     = false;
             DOMString initialValue;
};


partial interface CSS {
    static void registerProperty(PropertyDescriptor descriptor);
    static void unregisterProperty(DOMString name);
};

Issues Index

Intermediate interpolated results of animations on custom properties must be able to generate a token stream representing their value. We should ensure that this is standard across implementations to avoid interop issues.
should @supports pay attention to type when considering custom properties? <https://github.com/w3c/css-houdini-drafts/issues/118>