CSS Extensions

Unofficial Proposal Draft,

This version:
http://tabatkins.github.io/specs/css-aliases/
Issue Tracking:
Inline In Spec
GitHub Issues
Editor:
Tab Atkins (Google)
Suggest an Edit for this Spec:
GitHub Editor

Abstract

This specification defines methods for authors to extend and enhance various CSS features.

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, in speech, etc.

Status of this document

1. Introduction

When authoring CSS, one often encounters significant repetition in certain features. For example, a given media query might be repeated in several places, or a selector meant to apply to all heading elements requires specifying :matches(h1, h2, h3, h4, h5, h6) in every location that uses it.

This repetition makes stylesheets more verbose and difficult to read, and also affects maintenance, as the author has to keep each repetition in sync when making any changes.

This specification defines methods for extending several CSS features so that a long or repeatedly-used value can be given a short, memorable name instead, or a feature can be given a more complex definition controlled by a scripting language. This makes stylesheets easier to read, and more powerful in general, as authors can extend the feature-set of CSS themselves rather than waiting for standards bodies to define new features for them.

2. Extension Names

All extensions defined in this specification use a common syntax for defining their ”names”: the <extension-name> production. An <extension-name> is any identifier that starts with two dashes (U+002D HYPHEN-MINUS), like --foo, or even exotic names like -- or ------. The CSS language will never use identifiers of this form for any language-defined purpose, so it’s safe to use them for author-defined purposes without ever having to worry about colliding with CSS-defined names.

3. Custom Selectors

A custom selector is defined with the @custom-selector rule:

@custom-selector = @custom-selector <extension-name> <selector-list> ;

This defines a custom selector which is written as a pseudo-class with the given <extension-name>, and represents a :matches() selector using the provided <selector-list> as its argument.

For example, if an author wanted to easily refer to all heading elements in their HTML document, they could create an alias:
@custom-selector :--heading h1, h2, h3, h4, h5, h6;

:--heading { /* styles for all headings */ }
:--heading + p { /* more styles */ }
/* etc */

3.1. Script-based Custom Selectors

This one’s more complicated than MQs. Brian Kardell came up with a good proposal for evaluating selectors as JS functions that return a boolean, which had decent performance characteristics by specifying the qualities of the element it was based on (which determined when it would be called).
<script>
CSS.customSelector.set("_foo",
                     {"predicate": function(el){...},
                       "matches": "a"});
</script>

"matches" is an optional selector specifying what subset of elements the custom selector is valid for. The selector is automatically false for elements that don’t match, and the predicate isn’t called.

By default, the predicate is called whenever there’s a mutation in an element that matches the "matches" selector, or one of its descendants.

You should be able to suppress the auto-calling, and be able to trigger the predicate to run manually. That way you can use mutation listeners manually to only call the predicate when necessary.

We should probably offer some sugar for filtering the list of mutations that trigger the predicate to be called. Maybe just a list of attributes that you’ll be caring about? And/or tagnames?

Maybe let the pseudo-class also accept an argument, and pass it (as a serialized string) as a second argument to the predicate. :_foo would pass null, while :_foo() would pass "".

3.2. CSSOM

Fill in.

4. Custom Functions

Interesting possibilities here. Definitely need some way to define custom functions in CSS. This would, for example, let people define whatever color function they want, such as implementing the HUSL color space.

Definitely need a JS interface. What options are needed?

Call time/frequency:

We can take some cues from my thoughts on a random() function. It needs per-instance, per-element&instance, and per "identifier", so you can reuse the same value in multiple spots. That last one can probably be handled manually by the JS, so we don’t have to privilege a particular argument as an identifier.

We’d need to provide the context in which it’s used. Which property, for example. Should we allow them to be used in other places, or should we just define more contextual locations as we go? That is, should we allow custom-defined functions in @supports with this API, or should we add a .customSupports map? I suspect that individual cases will have their own useful contextual information, so it’s better to specialize each instance of custom functions.

How much can we do in pure CSS? Being able to substitute values depending on MQs or support queries would be useful. To get *real* use out of it, though, I suspect we’d need fuller support for conditionals, likely in the form of SASS’s @if or something similar.

5. Custom Selector Combinators

Selectors are made of two pieces: simple selectors, and combinators. We should allow custom combinators too.

This is JS-only, because it’s transforming elements, not filtering them, and you can’t express any useful transformations in pure CSS.

You provide a function which, when given an element, produces a list of zero or more elements.

For examples, with div /--foo/ span, the CSS engine will match the first part of the selector and find all the div elements. It passes that list to the function registered for the --foo combinator, and expects to get a new list of elements returned. It then continues on its way, filtering that list to include only span elements, etc.

A child combinator would be something like:

CSS.customCombinator.set("--child", function(el) {
    return el.children;
  });

Then div /--child/ span would be identical to div > span.

If we generalize a selector with a custom combinator to A /--custom/ B, then the UA would automatically call the --custom function whenever new elements match A. If elements stop matching A, it won’t bother; it’ll just drop them from the result.

Alternately, the function could take a list of elements (all the elements matching A) and return a new list of elements. This would be a bit more complicated for the author, but would allow more variety in the types of combinators that could be defined, as you could define things that depend on the entire set of matched elements. For example, you could define A /nth 1/ B to give only the first element from the set of A matches.

(Maybe we allow both variants, since the per-element one is easier to optimize and program against, but the per-set one allows some useful stuff.)

Similarly to custom pseudo-classes, we’d allow arguments, with them parsed eagerly per-instance and passed to the combinator function.

If we do the per-element combinator function, we could potentially cache the results, so that it never needs to be called again for the same element. Possibly have a flag that turns off this behavior, so that you’re guaranteed to be called again.

6. Custom At-Rules

This one’s even less developed, but it would be interesting to allow custom at-rules as well. It’s definitely pure-JS as well.

Unsure exactly what’s best here. Possibly register a callback per rule, which is called with the prelude/contents of the at-rule?

Should we do the callback approach, or just maintain a list of custom at-rules and let scripts parse them themselves? Unfortunately, the latter means we’d have to have a special mechanism to alert scripts when new at-rules get added or removed.

For a lot of these at-rules, we may want a way to know when they’re "applied"—when, according to the built-in at-rules like @media and @supports, the rule would be applied.

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.

Requirements for Responsible Implementation of CSS

The following sections define several conformance requirements for implementing CSS responsibly, in a way that promotes interoperability in the present and future.

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

Implementations of CR-level Features

Once a specification reaches the Candidate Recommendation stage, implementers should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec, and should avoid exposing a prefixed variant of that feature.

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.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 4. 14 August 2018. WD. URL: https://www.w3.org/TR/css-values-4/
[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
[SELECTORS-4]
Elika Etemad; Tab Atkins Jr.. Selectors Level 4. 2 February 2018. WD. URL: https://www.w3.org/TR/selectors-4/

Issues Index

This one’s more complicated than MQs. Brian Kardell came up with a good proposal for evaluating selectors as JS functions that return a boolean, which had decent performance characteristics by specifying the qualities of the element it was based on (which determined when it would be called).
<script>
CSS.customSelector.set("_foo",
                     {"predicate": function(el){...},
                       "matches": "a"});
</script>

"matches" is an optional selector specifying what subset of elements the custom selector is valid for. The selector is automatically false for elements that don’t match, and the predicate isn’t called.

By default, the predicate is called whenever there’s a mutation in an element that matches the "matches" selector, or one of its descendants.

You should be able to suppress the auto-calling, and be able to trigger the predicate to run manually. That way you can use mutation listeners manually to only call the predicate when necessary.

We should probably offer some sugar for filtering the list of mutations that trigger the predicate to be called. Maybe just a list of attributes that you’ll be caring about? And/or tagnames?

Maybe let the pseudo-class also accept an argument, and pass it (as a serialized string) as a second argument to the predicate. :_foo would pass null, while :_foo() would pass "".

Fill in.
Interesting possibilities here. Definitely need some way to define custom functions in CSS. This would, for example, let people define whatever color function they want, such as implementing the HUSL color space.

Definitely need a JS interface. What options are needed?

Call time/frequency:

We can take some cues from my thoughts on a random() function. It needs per-instance, per-element&instance, and per "identifier", so you can reuse the same value in multiple spots. That last one can probably be handled manually by the JS, so we don’t have to privilege a particular argument as an identifier.

We’d need to provide the context in which it’s used. Which property, for example. Should we allow them to be used in other places, or should we just define more contextual locations as we go? That is, should we allow custom-defined functions in @supports with this API, or should we add a .customSupports map? I suspect that individual cases will have their own useful contextual information, so it’s better to specialize each instance of custom functions.

How much can we do in pure CSS? Being able to substitute values depending on MQs or support queries would be useful. To get *real* use out of it, though, I suspect we’d need fuller support for conditionals, likely in the form of SASS’s @if or something similar.

Selectors are made of two pieces: simple selectors, and combinators. We should allow custom combinators too.

This is JS-only, because it’s transforming elements, not filtering them, and you can’t express any useful transformations in pure CSS.

You provide a function which, when given an element, produces a list of zero or more elements.

For examples, with div /--foo/ span, the CSS engine will match the first part of the selector and find all the div elements. It passes that list to the function registered for the --foo combinator, and expects to get a new list of elements returned. It then continues on its way, filtering that list to include only span elements, etc.

A child combinator would be something like:

CSS.customCombinator.set("--child", function(el) {
    return el.children;
  });

Then div /--child/ span would be identical to div > span.

If we generalize a selector with a custom combinator to A /--custom/ B, then the UA would automatically call the --custom function whenever new elements match A. If elements stop matching A, it won’t bother; it’ll just drop them from the result.

Alternately, the function could take a list of elements (all the elements matching A) and return a new list of elements. This would be a bit more complicated for the author, but would allow more variety in the types of combinators that could be defined, as you could define things that depend on the entire set of matched elements. For example, you could define A /nth 1/ B to give only the first element from the set of A matches.

(Maybe we allow both variants, since the per-element one is easier to optimize and program against, but the per-set one allows some useful stuff.)

Similarly to custom pseudo-classes, we’d allow arguments, with them parsed eagerly per-instance and passed to the combinator function.

If we do the per-element combinator function, we could potentially cache the results, so that it never needs to be called again for the same element. Possibly have a flag that turns off this behavior, so that you’re guaranteed to be called again.

This one’s even less developed, but it would be interesting to allow custom at-rules as well. It’s definitely pure-JS as well.

Unsure exactly what’s best here. Possibly register a callback per rule, which is called with the prelude/contents of the at-rule?

Should we do the callback approach, or just maintain a list of custom at-rules and let scripts parse them themselves? Unfortunately, the latter means we’d have to have a special mechanism to alert scripts when new at-rules get added or removed.

For a lot of these at-rules, we may want a way to know when they’re "applied"—when, according to the built-in at-rules like @media and @supports, the rule would be applied.