CSS Values and Units Module Level 5

Editor’s Draft,

More details about this document
This version:
https://drafts.csswg.org/css-values-5/
Latest published version:
https://www.w3.org/TR/css-values-5/
Feedback:
CSSWG Issues Repository
Inline In Spec
Editors:
Tab Atkins (Google)
fantasai
Suggest an Edit for this Spec:
GitHub Editor

Abstract

This CSS module describes the common values and units that CSS properties accept and the syntax used for describing them in CSS property definitions.

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

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

Please send feedback by filing issues in GitHub (preferred), including the spec code “css-values” in the title, like this: “[css-values] …summary of comment…”. All issues and comments are archived. Alternately, feedback can be sent to the (archived) public mailing list www-style@w3.org.

This document is governed by the 2 November 2021 W3C Process Document.

1. Introduction

The value definition field of each CSS property can contain keywords, data types (which appear between < and >), and information on how they can be combined. Generic data types (<length> being the most widely used) that can be used by many properties are described in this specification, while more specific data types (e.g., <spacing-limit>) are described in the corresponding modules.

1.1. Module Interactions

This module supersedes [CSS-VALUES-4] which replaces and extends the data type definitions in [CSS21] sections 1.4.2.1, 4.3, and A.2.

1.2. Toggling Between Values: toggle()

The toggle() expression allows descendant elements to cycle over a list of values instead of inheriting the same value.

The following example makes <em> elements italic in general, but makes them normal if they’re inside something that’s italic:
em { font-style: toggle(italic; normal); }
The following example cycles markers for nested lists, so that a top level list has disc-shaped markers, but nested lists use circle, then square, then box, and then repeat through the list of marker shapes, starting again (for the 5th list deep) with disc.
ul { list-style-type: toggle(disc; circle; square; box); }

The syntax of the toggle() expression is:

toggle( <toggle-value> [ ';' <toggle-value> ]+ )

where <toggle-value> is any CSS value that is valid where the expression is placed. If any of the values inside are not valid, then the entire toggle() expression is invalid. The toggle() expression may be used as the value of any property, but must be the only component in that property’s value.

Note: This functional notation uses semicolons to separate arguments rather than the more typical comma because the values themselves can contain commas.

The toggle() notation is not allowed to be nested; nor may it contain attr() or calc() notations. Declarations containing such constructs are invalid.

The following toggle() examples are all invalid:
background-position: 10px toggle(50px, 100px);
/* toggle() must be the sole value of the property */

list-style-type: toggle(disc, 50px);
/* 50px isn’t a valid value of 'list-style-type' */

To determine the computed value of toggle(), first evaluate each argument as if it were the sole value of the property in which toggle() is placed to determine the computed value that each represents, called Cn for the n-th argument to toggle(). Then, compare the property’s inherited value with each Cn. For the earliest Cn that matches the inherited value, the computed value of toggle() is Cn+1. If the match was the last argument in the list, or there was no match, the computed value of toggle() is the computed value that the first argument represents.

Note: This means that repeating values in a toggle() short-circuits the list. For example toggle(1em; 2em; 1em; 4em) will be equivalent to toggle(1em; 2em).

Note: That toggle() explicitly looks at the computed value of the parent, so it works even on non-inherited properties. This is similar to the inherit keyword, which works even on non-inherited properties.

Note: That the computed value of a property is an abstract set of values, not a particular serialization [CSS21], so comparison between computed values should always be unambiguous and have the expected result. For example, a Level 2 background-position computed value is just two offsets, each represented as an absolute length or a percentage, so the declarations background-position: top center and background-position: 50% 0% produce identical computed values. If the "Computed Value" line of a property definition seems to define something ambiguous or overly strict, please provide feedback so we can fix it.

If toggle() is used on a shorthand property, it sets each of its longhands to a toggle() value with arguments corresponding to what the longhand would have received had each of the original toggle() arguments been the sole value of the shorthand.

For example, the following shorthand declaration:
margin: toggle(1px 2px, 4px, 1px 5px 4px);

is equivalent to the following longhand declarations:

margin-top:    toggle(1px; 4px; 1px);
margin-right:  toggle(2px; 4px; 5px);
margin-bottom: toggle(1px; 4px; 4px);
margin-left:   toggle(2px; 4px; 5px);

Note that, since 1px appears twice in the top margin and 4px appears twice in bottom margin, they will cycle between only two values while the left and right margins cycle through three. In other words, the declarations above will yield the same computed values as the longhand declarations below:

margin-top:    toggle(1px; 4px);
margin-right:  toggle(2px; 4px; 5px);
margin-bottom: toggle(1px; 4px);
margin-left:   toggle(2px; 4px; 5px);

which may not be what was intended.

2. Attribute References: the attr() function

attr

In all current engines.

Firefox1+Safari3.1+Chrome2+
Opera9+Edge79+
Edge (Legacy)12+IE8+
Firefox for Android?iOS Safari?Chrome for Android?Android WebView37+Samsung Internet?Opera Mobile10.1+

The attr() function substitutes the value of an attribute on an element into a property, similar to how the var() function substitutes a custom property value into a function.

attr() = attr( <q-name> <attr-type>? , <declaration-value>?)

<attr-type> = string | url | ident | color | number | percentage |
              length | angle | time | frequency | flex | <dimension-unit>

The <dimension-unit> production matches a literal "%" character (that is, a <delim-token> with a value of "%") or an ident whose value is any of the CSS units for <length>, <angle>, <time>, <frequency>, or <flex> values (such as px or ms).

The arguments of attr() are:

<q-name>

Gives the name of the attribute being referenced.

If no namespace is specified (just an identifier is given, like attr(foo)), the null namespace is implied. (This is usually what’s desired, as namespaced attributes are rare. In particular, HTML and SVG do not contain namespaced attributes.) As with attribute selectors, the case-sensitivity of <q-name> depends on the document language.

If attr() is used in a property applied to an element, it references the attribute of the given name on that element; if applied to a pseudo-element, the attribute is looked up on the pseudo-element’s originating element.

<attr-type>

Specifies what kind of CSS value the attribute’s value will be interpreted into (the attr()’s substitution value) and what, if any, special parsing will be done to the value.

The possible values and their behavior are defined in § 2.1 attr() Types.

Defaults to string if omitted.

<declaration-value>

Specifies a fallback value for the attr(), which will be substituted instead of the attribute’s value if the attribute is missing or fails to parse as the specified type.

If the <attr-type> argument is string, defaults to the empty string if omitted; otherwise, defaults to the guaranteed-invalid value if omitted.

If a property contains one or more attr() 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 attr() functions have been substituted.

Note that the default value need not be of the type given. For instance, if the type required of the attribute by the author is px, the default could still be auto, like in width: attr(size px, auto);.

2.1. attr() Types

The behavior of the attr() function depends partially on the value of the <attr-type> argument:

string

The substitution value is a CSS string, whose value is the literal value of the attribute. (No CSS parsing or "cleanup" of the value is performed.)

No value triggers fallback.

url

The substitution value is a CSS <url> value, whose url is the literal value of the attribute. (No CSS parsing or "cleanup" of the value is performed.)

Note: If url() was syntactically capable of containing functions, attr(foo url) would be identical to url(attr(foo string)).

No value triggers fallback.

ident

The substitution value is a CSS <custom-ident>, whose value is the literal value of the attribute, with leading and trailing ASCII whitespace stripped. (No CSS parsing of the value is performed.)

If the attribute value, after trimming, is the empty string, there is instead no substitution value.

If the <custom-ident>’s value is a CSS-wide keyword or default, there is instead no substitution value.

color

Parse a component value from the attribute’s value. If the result is a <hex-color> or a named color ident, the substitution value is that result as a <color>.

Otherwise there is no substitution value.

number

Parse a component value from the attribute’s value. If the result is a <number-token>, the result is the substitution value.

Otherwise, there is no substitution value.

percentage

Parse a component value from the attribute’s value. If the result is a <percentage-token>, the result is the substitution value.

Otherwise, there is no substitution value.

length
angle
time
frequency
flex

Parse a component value from the attribute’s value. If the result is a <dimension-token> whose unit matches the given type, the result is the substitution value.

Otherwise, there is no substitution value.

<dimension-unit>

Parse a component value from the attribute’s value. If the result is a <number-token>, the substitution value is a dimension with the result’s value, and the given unit.

Otherwise, there is no substitution value.

Do we want to allow math functions as attr values for all the numeric types? And color functions for "color"? I think we do, but I’d have to check the contents to make sure they don’t contain further reference functions; foo="rgb(var(--red), 0, 0)" needs to be illegal for attr(foo color).

This example shows the use of attr() to visually illustrate data in an XML file:
<stock>
  <wood length="12"/>
  <wood length="5"/>
  <metal length="19"/>
  <wood length="4"/>
</stock>

stock::before {
  display: block;
  content: "To scale, the lengths of materials in stock are:";
}
stock > * {
  display: block;
  width: attr(length em, 0px);
  height: 1em;
  border: solid thin;
  margin: 0.5em;
}
wood {
  background: orange url(wood.png);
}
metal {
  background: silver url(metal.png);
}

2.2. attr() Substitution

attr() and var() substitute at the same time, so I should probably rewrite substitute a var() to be more generally about "substitute a reference" and just use that for both of these functions.

attr() functions are substituted at computed-value time. If a declaration, once all attr() functions are substituted in, does not match its declared grammar, the declaration is invalid at computed-value time.

To substitute an attr():

  1. If the attr() function has a substitution value, replace the attr() function by the substitution value.

  2. Otherwise, if the attr() function has a fallback value as its last argument, replace the attr() function by the fallback value. If there are any var() or attr() references in the fallback, substitute them as well.

  3. Otherwise, the property containing the attr() function is invalid at computed-value time.

Acknowledgments

Firstly, the editors would like to thank all of the contributors to the previous level of this module.

Secondly, we would like to acknowledge L. David Baron and Mike Bremford for their comments and suggestions, which have improved Level 5.

Changes

Recent Changes

(This is a subset of .)

Additions Since Level 4

Additions since CSS Values and Units Level 4:

Security and Privacy Considerations

This specification mostly just defines units that are common to CSS specifications, and which present no security concerns.

Note: Does URL handling have a security concern? Probably.

This specification defines units that expose the user’s screen size and default font size, but both are trivially observable from JS, so they do not constitute a new privacy risk.

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.

Tests

Tests relating to the content of this specification may be documented in “Tests” blocks like this one. Any such block is non-normative.


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 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-CASCADE-5]
Elika Etemad; Miriam Suzanne; Tab Atkins Jr.. CSS Cascading and Inheritance Level 5. URL: https://andreubotella.com/csswg-auto-build/test/css-cascade-5/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley; Lea Verou. CSS Color Module Level 4. URL: https://andreubotella.com/csswg-auto-build/test/css-color/
[CSS-GRID-2]
Tab Atkins Jr.; Elika Etemad; Rossen Atanassov. CSS Grid Layout Module Level 2. URL: https://andreubotella.com/csswg-auto-build/test/css-grid-2/
[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin. CSS Syntax Module Level 3. URL: https://andreubotella.com/csswg-auto-build/test/css-syntax/
[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad. CSS Values and Units Module Level 4. URL: https://andreubotella.com/csswg-auto-build/test/css-values-4/
[CSS-VARIABLES-2]
CSS Variables Module Level 2 URL: https://drafts.csswg.org/css-variables-2/
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. URL: https://andreubotella.com/csswg-auto-build/test/css2/
[DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra Standard. Living Standard. URL: https://infra.spec.whatwg.org/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[SELECTORS-4]
Elika Etemad; Tab Atkins Jr.. Selectors Level 4. URL: https://andreubotella.com/csswg-auto-build/test/selectors/

Informative References

[CSS-BACKGROUNDS-3]
Bert Bos; Elika Etemad; Brad Kemper. CSS Backgrounds and Borders Module Level 3. URL: https://andreubotella.com/csswg-auto-build/test/css-backgrounds/
[CSS-SIZING-3]
Tab Atkins Jr.; Elika Etemad. CSS Box Sizing Module Level 3. URL: https://andreubotella.com/csswg-auto-build/test/css-sizing-3/

Issues Index

Do we want to allow math functions as attr values for all the numeric types? And color functions for "color"? I think we do, but I’d have to check the contents to make sure they don’t contain further reference functions; foo="rgb(var(--red), 0, 0)" needs to be illegal for attr(foo color).
attr() and var() substitute at the same time, so I should probably rewrite substitute a var() to be more generally about "substitute a reference" and just use that for both of these functions.