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 replaces and extends the data type definitions in [CSS21] sections 1.4.2.1, 4.3, and A.2.
2. Value Definition Syntax
The syntax described here is used to define the set of valid values for CSS properties. A property value can have one or more components.
2.1. Component value types
Component value types are designated in several ways:
- keyword values (such as auto, disc, etc.),
which appear literally, without quotes (e.g.
auto
) - basic data types, which appear between < and > (e.g., <length>, <percentage>, etc.).
- types that have the same range of values as a property bearing the same name (e.g., <‘border-width’>, <‘background-attachment’>, etc.). In this case, the type name is the property name (complete with quotes) between the brackets. Such a type does not include CSS-wide keywords such as inherit, and also does not include any top-level comma-separated-list multiplier (i.e. if property pairing is defined as [ <custom-ident> <integer>? ]#, then <‘pairing’> is equivalent to [ <custom-ident> <integer>? ], not <custom-ident> <integer> ]#).
- non-terminals that do not share the same name as a property. In this case, the non-terminal name appears between < and >, as in <spacing-limit>. Notice the distinction between <border-width> and <‘border-width’>: the latter is defined as the value of the border-width property, the former requires an explicit expansion elsewhere. The definition of a non-terminal is typically located near its first appearance in the specification.
Some property value definitions also include the slash (/), the comma (,), and/or parentheses as literals. These represent their corresponding tokens. Other non-keyword literal characters that may appear in a component value, such as “+”, must be written enclosed in single quotes.
Commas specified in the grammar are implicitly omissible in some circumstances, when used to separate optional terms in the grammar. Within a top-level list in a property or other CSS value, or a function’s argument list, a comma specified in the grammar must be omitted if:
- all items preceding the comma have been omitted
- all items following the comma have been omitted
- multiple commas would be adjacent (ignoring white space/comments), due to the items between the commas being omitted.
example( first? , second? , third? )
Given this grammar, writing example(first, second, third) is valid, as is example(first, second) or example(first, third) or example(second). However, example(first, , third) is invalid, as one of those commas are no longer separating two options; similarly, example(,second) and example(first,) are invalid. example(first second) is also invalid, as commas are still required to actually separate the options.
If commas were not implicitly omittable, the grammar would have to be much more complicated to properly express the ways that the arguments can be omitted, greatly obscuring the simplicity of the feature.
All CSS properties also accept the CSS-wide keyword values as the sole component of their property value.
For readability these are not listed explicitly in the property value syntax definitions.
For example, the full value definition of border-color is <color>{1,4} | inherit | initial | unset
(even though it is listed as <color>{1,4}
).
Note: This implies that, in general, combining these keywords with other component values in the same declaration results in an invalid declaration. For example, background: url(corner.png) no-repeat, inherit; is invalid.
2.2. Component value combinators
Component values can be arranged into property values as follows:
- Juxtaposing components means that all of them must occur, in the given order.
- A double ampersand (&&) separates two or more components, all of which must occur, in any order.
- A double bar (||) separates two or more options: one or more of them must occur, in any order.
- A bar (|) separates two or more alternatives: exactly one of them must occur.
- Brackets ([ ]) are for grouping.
Juxtaposition is stronger than the double ampersand, the double ampersand is stronger than the double bar, and the double bar is stronger than the bar. Thus, the following lines are equivalent:
a b | c || d && e f [ a b ] | [ c || [ d && [ e f ]]]
For reorderable combinators (||, &&), ordering of the grammar does not matter: components in the same grouping may be interleaved in any order. Thus, the following lines are equivalent:
a || b || c b || a || c
2.3. Component value multipliers
Every type, keyword, or bracketed group may be followed by one of the following modifiers:
- An asterisk (*) indicates that the preceding type, word, or group occurs zero or more times.
- A plus (+) indicates that the preceding type, word, or group occurs one or more times.
- A question mark (?) indicates that the preceding type, word, or group is optional (occurs zero or one times).
- A single number in curly braces ({A}) indicates that the preceding type, word, or group occurs A times.
- A comma-separated pair of numbers in curly braces ({A,B}) indicates that the preceding type, word, or group occurs at least A and at most B times. The B may be omitted ({A,}) to indicate that there must be at least A repetitions, with no upper bound on the number of repetitions.
- A hash mark (#) indicates that the preceding type, word, or group occurs one or more times, separated by comma tokens (which may optionally be surrounded by white space and/or comments). It may optionally be followed by the curly brace forms, above, to indicate precisely how many times the repetition occurs, like <length>#{1,4}.
- An exclamation point (!) after a group indicates that the group is required and must produce at least one value; even if the grammar of the items within the group would otherwise allow the entire contents to be omitted, at least one component value must not be omitted.
For repeated component values (indicated by *, +, or #), UAs must support at least 20 repetitions of the component. If a property value contains more than the supported number of repetitions, the declaration must be ignored as if it were invalid.
2.4. Combinator and Multiplier Patterns
There are a small set of common ways to combine multiple independent component values in particular numbers and orders. In particular, it’s common to want to express that, from a set of component value, the author must select zero or more, one or more, or all of them, and in either the order specified in the grammar or in any order.
All of these can be easily expressed using simple patterns of combinators and multipliers:
in order | any order | |
---|---|---|
zero or more | A? B? C?
| A? || B? || C?
|
one or more | [ A? B? C? ]!
| A || B || C
|
all | A B C
| A && B && C
|
Note that all of the "any order" possibilities are expressed using combinators, while the "in order" possibilities are all variants on juxtaposition.
2.5. Component values and white space
Unless otherwise specified, white space and/or comments may appear before, after, and/or between components combined using the above combinators and multipliers.
Note: In many cases, spaces will in fact be required between components in order to distinguish them from each other. For example, the value 1em2em would be parsed as a single <dimension-token> with the number 1 and the identifier em2em, which is an invalid unit. In this case, a space would be required before the 2 to get this parsed as the two lengths 1em and 2em.
2.6. Property value examples
Below are some examples of properties with their corresponding value definition fields
Property | Value definition field | Example value |
---|---|---|
orphans | <integer> | 3 |
text-align | left | right | center | justify | center |
padding-top | <length> | <percentage> | 5% |
outline-color | <color> | invert | #fefefe |
text-decoration | none | underline || overline || line-through || blink | overline underline |
font-family | [ <family-name> | <generic-family> ]# | "Gill Sans", Futura, sans-serif |
border-width | [ <length> | thick | medium | thin ]{1,4} | 2px medium 4px |
text-shadow | [ inset? && [ <length>{2,4} && <color>? ] ]# | none | 3px 3px rgba(50%, 50%, 50%, 50%), lemonchiffon 0 0 4px inset |
3. Combining Values: Interpolation, Addition, and Accumulation
Some procedures, for example transitions and animations,
combine two CSS property values.
The following combining operations—
- interpolation
-
Given two property values Va and VB,
produces an intermediate value Vresult at a distance of p along the interval between Va and VB such that p = 0 produces Va and p = 1 produces VB.
The range of p is (−∞, ∞) due to the effect of timing functions. As a result, this procedure must also define extrapolation behavior for p outside [0, 1].
- addition
-
Given two property values Va and VB,
returns the sum of the two properties, Vresult.
For addition that is not commutative
(for example, matrix multiplication) Va represents
the first term of the operation and VB represents
the second.
Note: While addition can often be expressed in terms of the same weighted sum function used to define interpolation, this is not always the case. For example, interpolation of transform matrices involves decomposing and interpolating the matrix components whilst addition relies on matrix multiplication.
- accumulation
-
Given two property values Va and VB,
returns the result, Vresult,
of combining the two operands
such that VB is treated as a delta from Va.
For accumulation that is not commutative
(for example, accumulation of mismatched transform lists) Va represents the first term of the operation
and VB represents the second.
Note: For many types of animation such as numbers or lengths, accumulation is defined to be identical to addition.
A common case where the definitions differ is for list-based types where addition may be defined as appending to a list whilst accumulation may be defined as component-based addition. For example, the filter list values blur(2) and blur(3), when added together would produce blur(2) blur(3), but when accumulated would produce blur(5).
These operations are only defined on computed values. (As a result, it is not necessary to define, for example, how to add a <length> value of 15pt with 5em since such values will be resolved to their canonical unit before being passed to any of the above procedures.)
If a value type does not define a specific procedure for addition or is defined as not additive, its addition operation is simply Vresult = Va.
If a value types does not define a specific procedure for accumulation, its accumulation operation is identical to addition.
4. Textual Data Types
Textual data types are used to represent identifiers or text. Aside from the casing of pre-defined keywords or as explicitly defined for a given property, no normalization is performed, not even Unicode normalization: the specified and computed value of a property are exactly the provided Unicode values after parsing (which includes character set conversion and escaping). [UNICODE] [CSS3SYN]
CSS identifiers, generically denoted by <ident>, consist of a sequence of characters conforming to the <ident-token> grammar. [CSS3SYN] Identifiers cannot be quoted; otherwise they would be interpreted as strings. CSS properties accept two classes of identifiers: pre-defined keywords and author-defined identifiers.
Note: The <ident> production is not meant for property value definitions—
All textual data types interpolate as discrete and are not additive.
4.1. Pre-defined Keywords
In the value definition fields, keywords with a pre-defined meaning appear literally. Keywords are CSS identifiers and are interpreted ASCII case-insensitively (i.e., [a-z] and [A-Z] are equivalent).
Value: collapse | separate
And here is an example of its use:
table { border-collapse: separate }
4.1.1. CSS-wide keywords: initial, inherit and unset
As defined above, all properties accept the CSS-wide keywords, which represent value computations common to all CSS properties.
The initial keyword represents the value specified as the property’s initial value. The inherit keyword represents the computed value of the property on the element’s parent. The unset keyword acts as either inherit or initial, depending on whether the property is inherited or not. All of these keywords are normatively defined in the Cascade module. [CSS3CASCADE]
Other CSS specifications can define additional CSS-wide keywords.
4.2. Author-defined Identifiers: the <custom-ident> type
Some properties accept arbitrary author-defined identifiers as a component value. This generic data type is denoted by <custom-ident>, and represents any valid CSS identifier that would not be misinterpreted as a pre-defined keyword in that property’s value definition. Such identifiers are fully case-sensitive (meaning they’re compared by codepoint), even in the ASCII range (e.g. example and EXAMPLE are two different, unrelated user-defined identifiers).
The CSS-wide keywords are not valid <custom-ident>s.
The default keyword is reserved
and is also not a valid <custom-ident>.
Specifications using <custom-ident> must specify clearly
what other keywords are excluded from <custom-ident>, if any—
When parsing positionally-ambiguous keywords in a property value, a <custom-ident> production can only claim the keyword if no other unfulfilled production can claim it.
Note: When designing grammars with <custom-ident>, the <custom-ident> should always be "positionally unambiguous", so that it’s impossible to conflict with any keyword values in the property.
4.3. Quoted Strings: the <string> type
Strings are denoted by <string> and consist of a sequence of characters delimited by double quotes or single quotes. They correspond to the <string-token> production in the CSS Syntax Module [CSS3SYN].
"\""
or as "\22"
).
Analogously for single quotes ('\''
or '\27'
).
content: "this is a 'string'."; content: "this is a \"string\"."; content: 'this is a "string".'; content: 'this is a \'string\'.'
It is possible to break strings over several lines, for aesthetic or other reasons, but in such a case the newline itself has to be escaped with a backslash (\). The newline is subsequently removed from the string. For instance, the following two selectors are exactly the same:
Since a string cannot directly represent a newline, to include a newline in a string, use the escape "\A". (Hexadecimal A is the line feed character in Unicode (U+000A), but represents the generic notion of "newline" in CSS.)
4.4. Resource Locators: the <url> type
The url() functional notation, denoted by <url>, represents a URL, which is a pointer to a resource. The typical syntax of a <url> is:
<url> = url( <string> <url-modifier>* )
body { background: url("http://www.example.com/pinkish.gif") }
A <url> may alternately be written without quotation marks around the URL itself, in which case it is specially-parsed as a <url-token> [CSS3SYN].
background: url("http://www.example.com/pinkish.gif"); background: url(http://www.example.com/pinkish.gif);
Note: This unquoted syntax is cannot accept a <url-modifier> argument and has extra escaping requirements: parentheses, whitespace characters, single quotes (') and double quotes (") appearing in a URL must be escaped with a backslash, e.g. url(open\(parens), url(close\)parens). (In quoted <string> url()s, only newlines and the character used to quote the string need to be escaped.) Depending on the type of URL, it might also be possible to write these characters as URL-escapes (e.g. url(open%28parens) or url(close%29parens)) as described in [URL].
Some CSS contexts (such as @import) also allow a <url> to be represented by a bare <string>, without the url() wrapper. In such cases the string behaves identically to a url() function containing that string.
@import url("base-theme.css"); @import "base-theme.css";
4.4.1. Relative URLs
In order to create modular style sheets that are not dependent on the absolute location of a resource, authors should use relative URLs. Relative URLs (as defined in [URL]) are resolved to full URLs using a base URL. RFC 3986, section 3, defines the normative algorithm for this process. For CSS style sheets, the base URL is that of the style sheet itself, not that of the styled source document. Style sheets embedded within a document have the base URL associated with their container.
When a <url> appears in the computed value of a property, it is resolved to an absolute URL, as described in the preceding paragraph. The computed value of a URL that the UA cannot resolve to an absolute URL is the specified value.
body { background: url("tile.png") }
is located in a style sheet designated by the URL:
http://www.example.org/style/basic.css
The background of the source document’s <body>
will be tiled with whatever image is described by the resource designated by the URL:
http://www.example.org/style/tile.png
The same image will be used regardless of the URL of the source document containing the <body>
.
4.4.1.1. Fragment URLs
To work around some common eccentriticites in browser URL handling, CSS has special behavior for fragment-only urls.
If a url()’s value starts with a U+0023 NUMBER SIGN (#
) character,
parse it as per normal for URLs,
but additionally set the local url flag of the url().
When matching a url() with the local url flag set, ignore everything but the URL’s fragment, and resolve that fragment against the current document that relative URLs are resolved against. This reference must always be treated as same-document (rather than cross-document).
When serializing a url() with the local url flag set, it must serialize as just the fragment.
What “browser eccentricities”?
Theoretically, browsers should re-resolve any relative URLs,
including fragment-only URLs,
whenever the document’s base URL changes
(such as through mutation of the base
element,
or calling pushState()
).
In many cases they don’t, however,
and so without special handling,
fragment-only URLs will suddenly become cross-document references
(pointing at the previous base URL)
and break in many of the places they’re used.
Since fragment-only URLs express a clear semantic of wanting to refer to the current document regardless of what its current URL is, this hack preserves the expected behavior at least in these cases.
4.4.2. Empty URLs
If the value of the url() is the empty string (like url("") or url()), the url must resolve to an invalid resource (similar to what the url about:invalid does).
Note: This matches the behavior of empty urls for embedded resources elsewhere in the web platform, and avoids excess traffic re-requesting the stylesheet or host document due to editting mistakes leaving the url() value empty, which are almost certain to be invalid resources for whatever the url() shows up in. Linking on the web platform does allow empty urls, so if/when CSS gains some functionality to control hyperlinks, this restriction can be relaxed in those contexts.
4.4.3. URL Modifiers
The url() function supports specifying additional <url-modifier>s, which change the meaning or the interpretation of the URL somehow. A <url-modifier> is either an <ident> or a functional notation.
This specification does not define any <url-modifier>s, but other specs may do so.
Note: A <url> that is either unquoted or not wrapped in url() notation cannot accept any <url-modifier>s.
5. Numeric Data Types
Numeric data types are used to represent quantities, indexes, positions, and other such values. Although many syntactic variations can exist in expressing the quantity (numeric aspect) in a given numeric value, the specified and computed value do not distinguish these variations: they represent the value’s abstract quantity, not its syntactic representation.
Properties may restrict numeric values to some range. If the value is outside the allowed range, unless otherwise specified, the declaration is invalid and must be ignored.
CSS theoretically supports infinite precision and infinite ranges for all value types; however in reality implementations have finite capacity. UAs should support reasonably useful ranges and precisions.
5.1. Integers: the <integer> type
Integer values are denoted by <integer>.
When written literally, an integer is one or more decimal digits 0 through 9 and corresponds to a subset of the <number-token> production in the CSS Syntax Module [CSS3SYN]. The first digit of an integer may be immediately preceded by - or + to indicate the integer’s sign.
5.1.1. Combination of <integer>
Interpolation of <integer> is defined as Vresult = round((1 - p) × Va + p × Vb); that is, interpolation happens in the real number space as for <number>s, and the result is converted to an <integer> by rounding to the nearest integer, with values halfway between adjacent integers rounded towards positive infinity.
Addition of <number> is defined as Vresult = Va + Vb
5.2. Real Numbers: the <number> type
Number values are denoted by <number>, and represent real numbers, possibly with a fractional component.
When written literally, a number is either an integer, or zero or more decimal digits followed by a dot (.) followed by one or more decimal digits and optionally an exponent composed of "e" or "E" and an integer. It corresponds to the <number-token> production in the CSS Syntax Module [CSS3SYN]. As with integers, the first character of a number may be immediately preceded by - or + to indicate the number’s sign.
The value <zero> represents a literal number with the value 0. Expressions that merely evaluate to a <number> with the value 0 (for example, calc(0)) do not match <zero>; only literal <number-token>s do.
5.2.1. Combination of <number>
Interpolation of <number> is defined as Vresult = (1 - p) × Va + p × Vb
Addition of <number> is defined as Vresult = Va + Vb
5.3. Numbers with Units: dimension values
The general term dimension refers to a number with a unit attached to it; and is denoted by <dimension>.
When written literally, a dimension is a number immediately followed by a unit identifier, which is an identifier. It corresponds to the <dimension-token> production in the CSS Syntax Module [CSS3SYN]. Like keywords, unit identifiers are ASCII case-insensitive.
CSS uses <dimension>s to specify distances (<length>), durations (<time>), frequencies (<frequency>), resolutions (<resolution>), and other quantities.
5.3.1. Compatible Units
When serializing computed values [CSSOM], compatible units (those related by a static multiplicative factor, like the 96:1 factor between px and in, or the the computed font-size factor between em and px) are converted into a single canonical unit. Each group of compatible units defines which among them is the canonical unit that will be used for serialization.
When serializing resolved values that are used values, all value types (percentages, numbers, keywords, etc.) that represent lengths are considered compatible with lengths. Likewise any future API that returns used values must consider any values represent distances/durations/frequencies/etc. as compatible with the relevant class of dimensions, and canonicalize accordingly.
5.3.2. Combination of Dimensions
Interpolation of compatible dimensions (for example, two <length> values) is defined as Vresult = (1 - p) × Va + p × Vb
Addition of compatible dimensions is defined as Vresult = Va + Vb
5.4. Percentages: the <percentage> type
Percentage values are denoted by <percentage>, and indicates a value that is some fraction of another reference value.
When written literally, a percentage consists of a number immediately followed by a percent sign %. It corresponds to the <percentage-token> production in the CSS Syntax Module [CSS3SYN].
Percentage values are always relative to another quantity, for example a length. Each property that allows percentages also defines the quantity to which the percentage refers. This quantity can be a value of another property for the same element, the value of a property for an ancestor element, a measurement of the formatting context (e.g., the width of a containing block), or something else.
5.4.1. Combination of <percentage>
Interpolation of <percentage> is defined as Vresult = (1 - p) × Va + p × Vb
Addition of <percentage> is defined as Vresult = Va + Vb
5.5. Mixing Percentages and Dimensions
In cases where a <percentage> can represent the same quantity as a dimension in the same component value position, and can therefore be combined with them in a calc() expression, the following convenience notations may be used in the property grammar:
- <length-percentage>
-
Equivalent to
[ <length> | <percentage> ]
, where the <percentage> will resolve to a <length>. - <frequency-percentage>
-
Equivalent to
[ <frequency> | <percentage> ]
, where the <percentage> will resolve to a <frequency>. - <angle-percentage>
-
Equivalent to
[ <angle> | <percentage> ]
, where the <percentage> will resolve to an <angle>. - <time-percentage>
-
Equivalent to
[ <time> | <percentage> ]
, where the <percentage> will resolve to a <time>.
On the other hand, the second and third arguments of the hsl() function can only be expressed as <percentage>s. Although calc() productions are allowed in their place, they can only combine percentages with themselves, as in calc(10% + 20%).
Note: Specifications should never alternate <percentage> in place of a dimension in a grammar unless they are compatible.
Note: More <TYPE-percentage> productions can be added in the future as needed. A <number-percentage> will never be added, as <number> and <percentage> can’t be combined in calc().
5.5.1. Combination of Percentage and Dimension Mixes
Interpolation of percengage-dimension value combinations (e.g. <length-percentage>, <frequency-percentage>, <angle-percentage>, <time-percentage> or equivalent notations) is defined as
- equivalent to interpolation of <length> if both Va and Vb are pure <length> values
- equivalent to interpolation of <percentage> if both Va and Vb are pure <percentage> values
- equivalent to converting both values into a calc() expression representing the sum of the dimension type and a percentage (each possibly zero) and interpolating each component individually (as a <length>/<frequency>/<angle>/<time> and as a <percentage>, respectively)
Addition of <percentage> is defined the same as interpolation except by adding each component rather than interpolating it.
6. Distance Units: the <length> type
Lengths refer to distance measurements and are denoted by <length> in the property definitions. A length is a dimension.
For zero lengths the unit identifier is optional (i.e. can be syntactically represented as the <number> 0). However, if a 0 could be parsed as either a <number> or a <length> in a property (such as line-height), it must parse as a <number>.
Properties may restrict the length value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
While some properties allow negative length values, this may complicate the formatting and there may be implementation-specific limits. If a negative length value is allowed but cannot be supported, it must be converted to the nearest value that can be supported.
In cases where the used length cannot be supported, user agents must approximate it in the actual value.
There are two types of length units: relative and absolute.
6.1. Relative lengths
Relative length units specify a length relative to another length. Style sheets that use relative units can more easily scale from one output environment to another.
The relative units are:
unit | relative to |
---|---|
em | font size of the element |
ex | x-height of the element’s font |
cap | cap height (the nominal height of capital letters) of the element’s font |
ch | average character advance of a narrow glyph in the element’s font, as represented by the “0” (ZERO, U+0030) glyph |
ic | average character advance of a fullwidth glyph in the element’s font, as represented by the “水” (CJK water ideograph, U+6C34) glyph |
rem | font size of the root element |
lh | line height of the element |
rlh | line height of the root element |
vw | 1% of viewport’s width |
vh | 1% of viewport’s height |
vi | 1% of viewport’s size in the root element’s inline axis |
vb | 1% of viewport’s size in the root element’s block axis |
vmin | 1% of viewport’s smaller dimension |
vmax | 1% of viewport’s larger dimension |
Child elements do not inherit the relative values as specified for their parent; they inherit the computed values.
6.1.1. Font-relative lengths: the em, ex, cap, ch, ic, rem, lh, rlh units
The font-relative lengths refer to the font metrics of the element on which they are used—
- em unit
- Equal to the computed value of the font-size property of the element on which it is used.
- ex unit
- Equal to the used x-height of the first available font [CSS3-FONTS]. The x-height is so called because it is often equal to the height of the lowercase "x". However, an ex is defined even for fonts that do not contain an "x". The x-height of a font can be found in different ways. Some fonts contain reliable metrics for the x-height. If reliable font metrics are not available, UAs may determine the x-height from the height of a lowercase glyph. One possible heuristic is to look at how far the glyph for the lowercase "o" extends below the baseline, and subtract that value from the top of its bounding box. In the cases where it is impossible or impractical to determine the x-height, a value of 0.5em must be assumed.
- cap unit
- Equal to the used cap-height of the first available font [CSS3-FONTS]. The cap-height is so called because it is approximately equal to the height of a capital Latin letter. However, a cap is defined even for fonts that do not contain Latin letters. The cap-height of a font can be found in different ways. Some fonts contain reliable metrics for the cap-height. If reliable font metrics are not available, UAs may determine the cap-height from the height of an uppercase glyph. One possible heuristic is to look at how far the glyph for the uppercase “O” extends below the baseline, and subtract that value from the top of its bounding box. In the cases where it is impossible or impractical to determine the cap-height, the font’s ascent must be used.
- ch unit
-
Equal to the used advance measure of the “0” (ZERO, U+0030) glyph
in the font used to render it.
(The advance measure of a glyph is its advance width or height,
whichever is in the inline axis of the element.)
This measurement is an approximation (and in monospace fonts, an exact measure) of a single narrow glyph’s advance measure, thus allowing measurements based on an expected glyph count.
Note: The advance measure of a glyph depends on writing-mode and text-orientation as well as font settings, text-transform, and any other properties that affect glyph selection or orientation.
In the cases where it is impossible or impractical to determine the measure of the “0” glyph, it must be assumed to be 0.5em wide by 1em tall. Thus, the ch unit falls back to 0.5em in the general case, and to 1em when it would be typeset upright (i.e. writing-mode is vertical-rl or vertical-lr and text-orientation is upright).
- ic unit
-
Equal to the used advance measure of the “水” (CJK water ideograph, U+6C34) glyph
found in the font used to render it.
This measurement is a typically an exact measure (in the few fonts with proportional fullwidth glyphs, an approximation) of a single fullwidth glyph’s advance measure, thus allowing measurements based on an expected glyph count.
In the cases where it is impossible or impractical to determine the ideographic advance measure, it must be assumed to be 1em.
- rem unit
- Equal to the computed value of font-size on the root element. When specified on the font-size property of the root element, the rem units refer to the property’s initial value.
- lh unit
- Equal to the computed value of the line-height property of the element on which it is used, converting normal to an absolute length by using only the metrics of the first available font.
- rlh unit
-
Equal to the computed value of line-height property on the root element,
converting normal to an absolute length as above.
Note: Setting the height of an element using either the lh or the rlh units does not enable authors to control the actual number of lines in that element. These units only enable length calculations based on the theoretical size of an ideal empty line; the size of actual lines boxes may differ based on their content. In cases where an author wants to limit the number of actual lines in an element, the max-lines property can be used instead.
We can potentially add more typographic units, like cicero, didot, etc. They’re just absolute units, and so can be done with the existing units, but is there enough desire for them (potentially for printing use-cases) that it would be worth adding them? Or should we just wait for Houdini Custom Units?
When used outside the context of an element
(such as in media queries),
these units refer to the metrics corresponding
to the initial values of the font and line-height properties.
When used in the value of the font-size property on the element they refer to,
they resolve against the computed metrics of the parent element—
6.1.2. Viewport-percentage lengths: the vw, vh, vi, vb, vmin, vmax units
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist. Note that the initial containing block’s size is affected by the presence of scrollbars on the viewport.
For paged media, the exact definition of the viewport-percentage lengths is deferred to [CSS3PAGE].
- vw unit
- Equal to 1% of the width of the initial containing block.
- vh unit
- Equal to 1% of the height of the initial containing block.
- vi unit
- Equal to 1% of the size of the initial containing block in the direction of the root element’s inline axis.
- vb unit
- Equal to 1% of the size of the initial containing block in the direction of the root element’s block axis.
- vmin unit
- Equal to the smaller of vw or vh.
- vmax unit
- Equal to the larger of vw or vh.
In situations where there is no root element or it hasn’t yet been styled (such as when evaluating media queries), the vi and vb units use the initial value of the writing-mode property to determine which axis they correspond to.
6.2. Absolute lengths: the cm, mm, Q, in, pt, pc, px units
The absolute length units are fixed in relation to each other and anchored to some physical measurement. They are mainly useful when the output environment is known. The absolute units consist of the physical units (in, cm, mm, pt, pc, Q) and the visual angle/pixel unit (px):
unit | name | equivalence |
---|---|---|
cm | centimeters | 1cm = 96px/2.54 |
mm | millimeters | 1mm = 1/10th of 1cm |
Q | quarter-millimeters | 1Q = 1/40th of 1cm |
in | inches | 1in = 2.54cm = 96px |
pc | picas | 1pc = 1/6th of 1in |
pt | points | 1pt = 1/72th of 1in |
px | pixels | 1px = 1/96th of 1in |
h1 { margin: 0.5in } /* inches */ h2 { line-height: 3cm } /* centimeters */ h3 { word-spacing: 4mm } /* millimeters */ h3 { letter-spacing: 1Q } /* quarter-millimeters */ h4 { font-size: 12pt } /* points */ h4 { font-size: 1pc } /* picas */ p { font-size: 12px } /* px */
All of the absolute length units are compatible, and px is their canonical unit.
For a CSS device, these dimensions are anchored either
- by relating the physical units to their physical measurements, or
- by relating the pixel unit to the reference pixel.
For print media at typical viewing distances, the anchor unit should be one of the physical units (inches, centimeters, etc). For screen media (including high-resolution devices), low-resolution devices, and devices with unusual viewing distances), it is recommended instead that the anchor unit be the pixel unit. For such devices it is recommended that the pixel unit refer to the whole number of device pixels that best approximates the reference pixel.
Note: If the anchor unit is the pixel unit, the physical units might not match their physical measurements. Alternatively if the anchor unit is a physical unit, the pixel unit might not map to a whole number of device pixels.
Note: This definition of the pixel unit and the physical units differs from previous versions of CSS. In particular, in previous versions of CSS the pixel unit and the physical units were not related by a fixed ratio: the physical units were always tied to their physical measurements while the pixel unit would vary to most closely match the reference pixel. (This change was made because too much existing content relies on the assumption of 96dpi, and breaking that assumption broke the content.)
Note: Values are case-insensitive and serialize as lower case, for example 1Q serializes as 1q.
The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm’s length. For a nominal arm’s length of 28 inches, the visual angle is therefore about 0.0213 degrees. For reading at arm’s length, 1px thus corresponds to about 0.26 mm (1/96 inch).
The image below illustrates the effect of viewing distance on the size of a reference pixel: a reading distance of 71 cm (28 inches) results in a reference pixel of 0.26 mm, while a reading distance of 3.5 m (12 feet) results in a reference pixel of 1.3 mm.
This second image illustrates the effect of a device’s resolution on the pixel unit: an area of 1px by 1px is covered by a single dot in a low-resolution device (e.g. a typical computer display), while the same area is covered by 16 dots in a higher resolution device (such as a printer).
7. Other Quantities
7.1. Angle Units: the <angle> type and deg, grad, rad, turn units
Angle values are <dimension>s denoted by <angle>. The angle unit identifiers are:
- deg
- Degrees. There are 360 degrees in a full circle.
- grad
- Gradians, also known as "gons" or "grades". There are 400 gradians in a full circle.
- rad
- Radians. There are 2π radians in a full circle.
- turn
- Turns. There is 1 turn in a full circle.
For example, a right angle is 90deg or 100grad or 0.25turn or approximately 1.57rad.
All <angle> units are compatible, and deg is their canonical unit.
For example, in the linear-gradient() function, the <angle> that determines the direction of the gradient is interpreted as a bearing angle.
Note: For legacy reasons, some uses of <angle> allow a bare 0 to mean 0deg. This is not true in general, however, and will not occur in future uses of the <angle> type.
7.2. Duration Units: the <time> type and s, ms units
Time values are dimensions denoted by <time>. The time unit identifiers are:
- s
- Seconds.
- ms
- Milliseconds. There are 1000 milliseconds in a second.
All <time> units are compatible, and s is their canonical unit.
Properties may restrict the time value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
7.3. Frequency Units: the <frequency> type and Hz, kHz units
Frequency values are dimensions denoted by <frequency>. The frequency unit identifiers are:
- Hz
- Hertz. It represents the number of occurrences per second.
- kHz
- KiloHertz. A kiloHertz is 1000 Hertz.
For example, when representing sound pitches, 200Hz (or 200hz) is a bass sound, and 6kHz (or 6khz) is a treble sound.
All <frequency> units are compatible, and hz is their canonical unit.
Note: Values are case-insensitive and serialize as lower case, for example 1Hz serializes as 1hz.
7.4. Resolution Units: the <resolution> type and dpi, dpcm, dppx units
Resolution units are dimensions denoted by <resolution>. The resolution unit identifiers are:
- dpi
- Dots per inch.
- dpcm
- Dots per centimeter.
- dppx
- x
- Dots per px unit.
The <resolution> unit represents the size of a single "dot" in a graphical representation by indicating how many of these dots fit in a CSS in, cm, or px. For uses, see e.g. the resolution media query in [MEDIAQ] or the image-resolution property defined in [CSS3-IMAGES].
All <resolution> units are compatible, and dppx is their canonical unit.
Note that due to the 1:96 fixed ratio of CSS in to CSS px, 1dppx is equivalent to 96dpi. This corresponds to the default resolution of images displayed in CSS: see image-resolution.
@media (min-resolution: 2dppx) { ... }
8. Data Types Defined Elsewhere
Some data types are defined in their own modules. This example talks about some of the most common ones used across several specifications.
8.1. Colors: the <color> type
The <color> data type is defined in [CSS3COLOR]. UAs that support CSS Color Level 3 or its successor must interpret <color> as defined therein.
8.1.1. Combination of <color>
Interpolation of <color> is defined as the independent interpolation of each component (red, green, blue, alpha) as a <number>. Interpolation is done between premultiplied colors (that is, colors for which the red, green, and blue components specified have been multiplied by the alpha).
Addition of <number> is likewise defined as the independent addition of each component as a <number> in premultiplied space.
Computed value needs to be able to represent
combinations of currentColor and an actual color.
Consider the value of text-emphasis-color in div { text-emphasis: circle; transition: all 2s; }
See Issue 445.
div:hover { text-emphasis-color: lime; }
em { color: red; }
8.2. Images: the <image> type
The <image> data type is defined in [CSS3-IMAGES]. UAs that support CSS Images Level 3 or its successor must interpret <image> as defined therein. UAs that do not yet support CSS Images Level 3 must interpret <image> as <url>.
8.2.1. Combination of <image>
Note: Interpolation of <image> is defined in CSS Images 3 §6 Interpolation.
Images are not additive.
8.3. 2D Positioning: the <position> type
The <position> value specifies the position of a object area (e.g. background image) inside a positioning area (e.g. background positioning area). It is interpreted as specified for background-position. [CSS3-BACKGROUND]
<position> = [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]
Note: The background-position property also accepts a three-value syntax. This has been disallowed generically because it creates parsing ambiguities when combined with other length or percentage components in a property value.
The canonical order when serializing is the horizontal component followed by the vertical component.
When specified in a grammar alongside other keywords, <length>s, or <percentage>s, <position> is greedily parsed; it consumes as many components as possible.
8.3.1. Combination of <position>
Interpolation of <position> is defined as the independent interpolation of each component (x, y) normalized as an offset from the top left corner as a <length-percentage>.
Addition of <position> is likewise defined as the independent addition each component (x, y) normalized as an offset from the top left corner as a <length-percentage>.
9. Functional Notations
A functional notation is a type of component value that can represent more complex types or invoke special processing. The syntax starts with the name of the function immediately followed by a left parenthesis (i.e. a <function-token>) followed by the argument(s) to the notation followed by a right parenthesis. White space is allowed, but optional, immediately inside the parentheses. Functions can take multiple arguments, which are formatted similarly to a CSS property value.
Some legacy functional notations, such as rgba(), use commas unnecessarily, but generally commas are only used to separate items in a list, or pieces of a grammar that would be ambiguous otherwise. If a comma is used to separate arguments, white space is optional before and after the comma.
background: url(http://www.example.org/image); color: rgb(100, 200, 50 ); content: counter(list-item) ". "; width: calc(50% - 2em);
9.1. Mathematical Expressions: calc(), min(), max(), and clamp()
The math functions, calc(), min(), max(), and clamp() allow mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values. A calc() function represents the result of the mathematical calculation it contains, using standard operator precedence rules; a min() or max() function represents the smallest (most negative) or largest (most positive), respectively, comma-separated calculation it contains; a clamp() function represents its central calculation, clamped according to its min and max calculations (given clamp(MIN, VAL, MAX), it is resolved exactly identically to max(MIN, min(VAL, MAX))).
A math function can be used wherever <length>, <frequency>, <angle>, <time>, <flex>, <resolution>, <percentage>, <number>, or <integer> values are allowed. Components of a math function can be literal values, other math functions, or other expressions, such as attr(), that evaluate to a valid argument type (like <length>).
Math functions can be used to combine value that use different units. In this example the author wants the margin box of each section to take up 1/3 of the space, so they start with 100%/3, then subtract the element’s borders and margins. (box-sizing can automatically achieve this effect for borders and padding, but a math function is needed if you want to include margins.)
section { float : left; margin : 1 em ; border : solid1 px ; width : calc ( 100 % / 3 -2 *1em - 2*1px); }
Similarly, in this example the gradient will show a color transition only in the first and last 20px of the element:
.fade { background-image : linear-gradient ( silver0 % , white20 px , whitecalc ( 100 % -20 px ), silver100 % ); }
Math functions can also be useful just to express values in a more natural, readable fashion, rather than as an obscure decimal. For example, the following sets the font-size so that exactly 35em fits within the viewport, ensuring that roughly the same amount of text always fills the screen no matter the screen size.
:root { font-size : calc ( 100 vw / 35 ); }
Functionality-wise, this is identical to just writing font-size: 2.857vw, but then the intent (that 35em fills the viewport) is much less clear to someone reading the code; the later reader will have to reverse the math themselves to figure out that 2.857 is meant to approximate 100/35.
min(), max(), and clamp() can be used to make sure a value doesn’t exceed a "safe" limit: For example, "responsive type" that sets font-size with viewport units might still want a minimum size to ensure readability:
.type { /* Set font-size to 10x the average of vw and vh, but don’t let it go below 12px. */ font-size : max ( 10 * (1vw + 1vh) / 2, 12px); }
Note: Full math expressions are allowed in each of the arguments; there’s no need to nest a calc() inside! You can also provide more than two arguments, if you have multiple constraints to apply.
.type { /* Force the font-size to stay between 12px and 100px */ font-size : clamp ( 12 px , 10 * (1vw + 1vh) / 2, 100px); }
If alternate resolution mechanics are desired they can be achieved by combining clamp() with min() or max():
- To have MAX win over MIN:
-
clamp(min(MIN, MAX), VAL, MAX). If you want to avoid repeating the MAX calculation, you can just reverse the nesting of functions that clamp() is defined against—
min(MAX, max(MIN, VAL)). - To have MAX and MIN "swap" when they’re in the wrong order:
-
clamp(min(MIN, MAX), VAL, max(MIN, MAX)). Unfortunately, there’s no easy way to do this without repeating the MIN and MAX terms.
9.1.1. Syntax
The syntax of a math function is:
<calc()> = calc( <calc-sum> ) <min()> = min( <calc-sum># ) <max()> = max( <calc-sum># ) <clamp()> = clamp( <calc-sum>#{3} ) <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]* <calc-product> = <calc-value> [ [ '*' | '/' ] <calc-value> ]* <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
In addition, whitespace is required on both sides of the + and - operators. (The * and / operaters can be used without white space around them.)
UAs must support math function expressions of at least 20 terms,
where each NUMBER
, DIMENSION
, or PERCENTAGE
is a term.
If a math function contains more than the supported number of terms,
it must be treated as if it were invalid.
9.1.2. Type Checking
A math function can be many possible types, such as <length>, <number>, etc., depending on the expression it contains, as defined below. It can be used anywhere a value of that type is allowed.
Additionally, math functions that resolve to <number> can be used in any place that only accepts <integer>. (It gets rounded to the nearest integer, as specified in §9.1.4 Range Checking.)
Operators form sub-expressions, which gain types based on their arguments.
Note: In previous versions of this specification, multiplication and division were limited in what arguments they could take, to avoid producing more complex intermediate results (such as 1px * 1em, which is <length>²) and to make division-by-zero detectable at parse time. This version now relaxes those restrictions.
Math functions allow arbitrary expressions, so long as the expression as a whole resolves to a singular unit according to the following rules:
-
At a + or - sub-expression, attempt to add the types of the left and right arguments. If this returns failure, the entire math function is invalid. Otherwise, the sub-expression’s type is the returned type.
-
At a * sub-expression, multiply the types of the left and right arguments. The sub-expression’s type is the returned result.
-
At a / sub-expression, let left type be the result of finding the types of its left argument, and right type be the result of finding the types of its right argument and then inverting it.
The sub-expression’s type is the result of multiplying the left type and right type.
-
Anything else is a terminal value, whose type is determined based on its CSS type:
- <number>
- <integer>
-
the type is «[ ]» (empty map)
- <length>
-
the type is «[ "length" → 1 ]»
- <angle>
-
the type is «[ "angle" → 1 ]»
- <time>
-
the type is «[ "time" → 1 ]»
- <frequency>
-
the type is «[ "frequency" → 1 ]»
- <resolution>
-
the type is «[ "resolution" → 1 ]»
- <flex>
-
the type is «[ "flex" → 1 ]»
- <percentage>
-
If, in the context in which the math function is placed, <percentage>s are resolved relative to another type of value (such as in width, where <percentage> is resolved against a <length>), and that other type is not <number>, the type is determined as the other type.
Otherwise, the type is «[ "percent" → 1 ]».
- anything else
-
The math function is invalid.
In all cases, the associated percent hint is null.
- <number>
-
The type of a calc() expression is the type of its contained expression. The type of a min(), max(), or clamp() expression is the result of adding the types of its comma-separated expressions. If the result is failure, the entire math function is invalid.
A math function resolves to <number>, <length>, <angle>, <time>, <frequency>, <resolution>, <flex>, or <percentage> according to which of those productions its type matches. (These categories are mutually exclusive.) If it can’t match any of these, the math function is invalid.
Division by zero is possible, which introduces certain complications. Math functions follow IEEE-754 semantics for these operations:
-
Dividing a positive value by zero produces +∞.
-
Dividing a negative value by zero produces −∞.
-
Adding or subtracting ±∞ to anything produces the appropriate infinity, unless a following rule would define it as producing NaN.
-
Multiplying any value by ±∞ produces the appropriate infinity, unless a following rule would define it as producing NaN.
-
Dividing any value by ±∞ produces zero, unless a following rule would define it as producing NaN.
-
Dividing zero by zero, dividing ±∞ by ±∞, multiplying 0 by ±∞, adding +∞ to −∞ (or the equivalent subtractions) produces NaN.
-
Any operation with at least one NaN argument produces NaN.
Additionally, IEEE-754 introduces the concept of "negative zero", which must be tracked within a calculation and between nested calculations:
-
Negative zero (0-) can be produced literally by negating a zero (-0), or by a multiplication or division that produces zero with exactly one negative argument (such as -5 * 0 or 1 / (-1 / 0)).
Note: Note that, outside of math functions, -0 just produces a "standard" zero, identical to 0—
CSS as a whole doesn’t recognize the concept of signed zeros. Negative zeros also don’t escape a math function; as detailed below, they’re "censored" away into an "unsigned" zero. -
-0 + -0 or -0 - 0 produces 0-. All other additions or subtractions that would produce a zero produce 0+.
-
Multiplying or dividing 0- with a positive number (including 0+) produces a negative result (either 0- or −∞), while multiplying or dividing 0- with a negative number produces a positive result.
(In other words, multiplying or dividing with 0- follows standard sign rules.)
-
When comparing 0+ and 0-, 0- is less than 0+. For example, min(0, -0) must produce 0-, max(0, -0) must produce 0+, and clamp(0, -0, 1) must produce 0+.
If a top-level calculation (a math function not nested inside of another math function) would produce a NaN, it instead produces +∞. If a top-level calculation would produce 0-, it instead produces the standard "unsigned" zero.
On the other hand, calc(1 / calc(-5 * 0)) produces −∞,
same as calc(1 / (-5 * 0))—
Note: Algebraic simplifications do not affect the validity of a math function or its resolved type. For example, calc(5px - 5px + 10s) and calc(0 * 5px + 10s) are both invalid due to the attempt to add a length and a time.
Note: Note that <percentage>s relative to <number>s,
such as in opacity,
are not combinable with those numbers—
Note: Because <number-token>s are always interpreted as <number>s or <integer>s, "unitless 0" <length>s aren’t supported in math functions. That is, width: calc(0 + 5px); is invalid, because it’s trying to add a <number> to a <length>, even though both width: 0; and width: 5px; are valid.
Note: Altho there are a few properties in which a bare <number> becomes a <length> at used-value time (specifically, line-height and tab-size), <number>s never become "length-like" in calc(). They always stay as <number>s.
9.1.3. Computed Value
The computed value of a calc() function is the expression with all components computed. The computed value of a min(), max(), or clamp() function is the comma-separated list of expressions, with each expression having all its component computed.
Where percentages are not resolved at computed-value time, they are not resolved in math functions, e.g. calc(100% - 100% + 1em) resolves to calc(1em + 0%), not to 1em. If there are special rules for computing percentages in a value (e.g. the height property), they apply whenever a math function contains percentages.
At this time, all units can be absolutized to a single unit per type at computed-value time, so at that point the math function can be reduced to just a <number>, a <percentage>, and a single absolute <dimension> of the appropriate type, per expression.
Due to this, background-position computation preserves the percentage in a calc() whereas font-size will compute such expressions directly into a length.
Given the complexities of width and height calculations on table cells and table elements, math expressions mixing both percentages and lengths for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables MAY be treated as if auto had been specified.
9.1.4. Range Checking
Parse-time range-checking of values is not performed within math functions, and therefore out-of-range values do not cause the declaration to become invalid. However, the value resulting from an expression must be clamped to the range allowed in the target context. Clamping is performed on computed values to the extent possible, and also on used values if computation was unable to sufficiently simplify the expression to allow range-checking. (Clamping is not performed on specified values.)
Note: This requires all contexts accepting calc() to define their allowable values as a closed (not open) interval.
Note: By definition, ±∞ are outside the allowed range for any property, and will clamp to the minimum/maximum value allowed. Even for properties that explicitly allow infinity as a keyword value, such as animation-iteration-count, will end up clamping ±∞, as math functions can’t resolve to keyword values; the numeric part of the property’s syntax still has a minimum/maximum value.
Additionally, if a math function that resolves to <number> is used somewhere that only accepts <integer>, the computed value and used value are rounded to the nearest integer, in the same manner as clamping, above. The rounding method must be the same as is used for animations of integer values.
width: calc(5px - 10px); width: calc(-5px); width: 0px;
Note however that width: -5px is not equivalent to width: calc(-5px)! Out-of-range values outside calc() are syntactically invalid, and cause the entire declaration to be dropped.
9.1.5. Serialization
This section is still under discussion.
-
Simplify the expression inside of it.
-
If this simplification process results in only a single value (one <number>, one <dimension>, or one <percentage>), and the value being serialized is a computed value or later, serialize it just as that one value, without the calc() wrapper. If this value is outside the allowed range for the context, it must be clamped to the nearest allowed value.
-
Otherwise, serialize the summation, prefix the result with "calc(" and suffix it with ")", then return it.
-
For each comma-separated expression inside of it, simplify the expression.
-
Let s initially be "min(" or "max(", as appropriate.
-
Serialize each summation, then join them into a single string, with ", " between each term. Append the result to s.
-
Append ")" to s, then return it.
-
Replace any calc() values with parentheses containing their contents.
-
Resolve all multiplications and divisions.
-
Combine identical units.
-
Return the result.
Note: The value-computation process can transform disparate units into identical ones. For example, em and px are obviously different at specified-value time, but at computed-value time they’re both absolutized to px.
The result must be a summation of unique units and/or math functions. (Terms with a value of zero must be preserved in this summation.)
-
Sort the terms in the following order:
-
The number, if present
-
The percentage, if present
-
The dimensions, ordered by their units ASCII case-insensitive alphabetically
-
The min() and max() functions, in the order they appeared in the original expression.
-
-
Serialize all the terms, then join them into a single string, with " + " between each term. Return the result.
A value like calc(20px + 0%) would serialize as calc(0% + 20px), maintaining both terms in the serialized value. (It’s important to maintain zero-valued terms, so the calc() doesn’t suddenly "change shape" in the middle of a transition when one of the values happens to have a zero value temporarily. This also removes the need to "pick a unit" when all the terms are zero.)
A value like calc(20px + 2em) would serialize as calc(2em + 20px) as a specified value (maintaining both units as they’re incompatible at specified-value time, but sorting them alphabetically), or as something like 52px as a computed value (em values are converted to absolute lengths at computed-value time, so assuming 1em = 16px, they combine into 52px, which then drops the calc() wrapper.)
See [CSSOM] for further information on serialization.
9.2. Toggling Between Values: toggle()
The toggle() expression allows descendant elements to cycle over a list of values instead of inheriting the same value.
<em>
elements italic in general,
but makes them normal if they’re inside something that’s italic:
em { font-style: toggle(italic, normal); }
ul { list-style-type: toggle(disc, circle, square, box); }
The syntax of the toggle() expression is:
toggle( <toggle-value># )
where <toggle-value> is any CSS value that is valid where the expression is placed, and that doesn’t contain any top-level commas. 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.
The toggle() notation is not allowed to be nested; nor may it contain attr() or calc() notations. Declarations containing such constructs are 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.
margin: toggle(1px 2px, 4px, 1px 5px 3px);
is equivalent to the following longhand declarations:
margin-top: toggle(1px, 4px, 1px); margin-right: toggle(2px, 4px, 5px); margin-bottom: toggle(1px, 4px, 3px); margin-left: toggle(2px, 4px, 5px);
Note that, since 1px appears twice in the top and bottom margins, 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, 3px); margin-right: toggle(2px, 4px, 5px); margin-bottom: toggle(1px, 3px); margin-left: toggle(2px, 4px, 5px);
which may not be what was intended.
9.3. Attribute References: attr()
The attr() function is allowed as a component value in properties applied to an element or pseudo-element. It returns the value of an attribute on the element. If used on a pseudo-element, it returns the value of the attribute on the pseudo-element’s originating element.
The computed value of the attr() expression is the value of the attribute with the specified name on the element, according to the rules given below.
Note: In CSS2.1 [CSS21], the attr() expression always returns a string. In CSS3, the attr() expression can return many different types. The attr() expression cannot return everything, for example it cannot do counters, named strings, quotes, or keyword values such as auto, nowrap, or baseline. This is intentional, as the intent of the attr() expression is not to make it possible to describe a presentational language’s formatting using CSS, but to enable CSS to take semantic data into account.
The new syntax for the attr() expression is:
attr( <attr-name> <type-or-unit>? [ , <attr-fallback> ]? )
where <attr-name> is a CSS qualified name (the qname production in [CSS3NAMESPACE]) that represents an attribute name. (In the absence of namespacing, this will just be a CSS identifier.) As with attribute selectors, the case-sensitivity of <attr-name> depends on the document language.
The optional <type-or-unit> argument is a keyword drawn from the list below that tells the UA how to interpret the attribute value, and defines a type for the attr() expression. If omitted, string is implied.
The optional <attr-fallback> argument represents a fallback value, which is used if the named attribute is missing, or its value cannot be parsed into the given type or is invalid/out-of-range for the property. If it’s absent, the default value for the given <type-or-unit> (from the list below) is implied.
Note: Unlike <toggle-value>s, an attr() <attr-fallback> value may contain top-level commas, as it is always the last argument in the functional notation.
The attr() expression is only valid if:
- the attr() expression’s type is valid where the attr() expression is placed,
- the namespace prefix of the attribute name, if any, is defined,
- the <attr-fallback> is valid where the attr() expression is placed,
- the <attr-fallback> does not contain another attr() expression,
- and, if the attr() expression is not the sole component value of a property, the <attr-fallback> matches the attr()’s type
If the attr() is used alongside other values to form the full property value, however, then the default value must match the attr()'s type. For example, box-shadow: attr(size px, inset) 5px 10px blue; is invalid, even though it would create a valid declaration if you substituted the attr() expression with either a px length or the inset keyword.
If the specified attribute exists on the element, the value of the attribute must be parsed as required by the <type-or-unit> argument (as defined in the list below). Unless the type is string, it must first be stripped of leading and trailing white space. The resulting value is the attr() expression’s value. If the value did not parse as required, the attr() expression’s value is its fallback value.
The <type-or-unit> keywords are:
- string
-
The attribute value is taken as the contents of a CSS <string>.
The default is the empty string.
Note: This does not reparse the attribute value with the CSS parser. So, for example, an attribute whose value is "\51" will produce a string containing those three characters, not a string containing "Q" (the character that the escape would evaluate to).
- color
- The attribute value must parse as a <hash-token> or <ident-token>, and be successfully interpreted as a <color>. The default is currentcolor.
- url
- The attribute value is taken as the contents of a CSS <string>. It is interpreted as a quoted string within the url() notation. The default is about:invalid, which is a URL defined (in Appendix A) to point to a non-existent document with a generic error condition. Relative URLs must be made absolute according to the rules of the document language as applied to URLs originating from the element; they are not relative to the style sheet.
- integer
- The attribute value must parse as a <number-token>, and be successfully interpreted as an <integer>. The default is 0, or else the property’s minimum value if 0 is not valid for the property. The default must also be used if the property in question only accepts integers within a certain range and the attribute is out of range.
- number
- The attribute value must parse as a <number-token>, and is interpreted as an <number>. The default is 0, or else the property’s minimum value if 0 is not valid for the property. The default must also be used if the property in question only accepts integers within a certain range and the attribute is out of range.
- length
- angle
- time
- frequency
- angle
- The attribute value must parse as a <dimension-token>, and be successfully interpreted as the specified type. The default is 0 in the relevant units, or else the property’s minimum value if 0 in the relevant units is not valid for the property. The default must also be used if the property in question only accepts values within a certain range (e.g. positive lengths or angles from 0 to 90deg) and the attribute is out of range (e.g. a negative length or 180deg). If the unit is a relative length, it must be computed to an absolute length.
- %
- A keyword matching one of the <length>, <angle>, <time>, or <frequency> units
- The attribute value must parse as a <number-token>, and is interpreted as a dimension with the specified unit. The default is 0 in the relevant units, or else the property’s minimum value if 0 in the relevant units is not valid for the property. The default must also be used if the property in question only accepts values within a certain range (e.g. positive lengths or angles from 0 to 90deg) and the attribute is out of range (e.g. a negative length or 180deg). If the unit is a relative length, it must be computed to an absolute length.
<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); /* default 0 */ height: 1em; border: solid thin; margin: 0.5em; } wood { background: orange url(wood.png); } metal { background: silver url(metal.png); }
content: attr(title color); /* 'content' doesn’t accept colors */ content: attr(end-of-quote string, inherit) close-quote; /* the 'inherit' value is not allowed there, since the result would be 'inherit close-quote', which is invalid. */ margin: attr(vertical length) attr(horizontal deg); /* deg units are not valid at that point */ color: attr(color); /* 'color' doesn’t accept strings */
Note: The attr() expression cannot currently fall back onto another attribute. Future versions of CSS may extend attr() in this direction.
10. Appendix A: IANA Considerations
10.1. Registration for the about:invalid
URL scheme
This sections defines and registers the about:invalid
URL,
in accordance with the registration procedure defined in [RFC6694].
The official record of this registration can be found at http://www.iana.org/assignments/about-uri-tokens/about-uri-tokens.xhtml.
Registered Token | invalid
|
---|---|
Intended Usage | The about:invalid URL references a non-existent document with a generic error condition.
It can be used when a URL is necessary, but the default value shouldn’t be resolveable as any type of document.
|
Contact/Change controller | CSS WG <www-style@w3.org> (on behalf of W3C) |
Specification | CSS Values and Units Module Level 3 |
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 Koji Ishii and Xidorn Quan for their comments and suggestions, which have improved Level 4.
Changes
Changes since the 10 October 2018 Working Draft consist of synchronizing with the recent changes in CSS Level 3.
Changes since the 14 August 2018 Working Draft:
- Added rules for interpolation per value type, and clarified computed values.
Changes since Level 3:
- Added the vi, vb, ic, cap, lh and rlh units.
- Added min(), max(), and clamp() functional notations.
- Added unit arithmetic to calc().
- Added toggle() (punted from level 3 originally).
- Added unit algebra, cribbing from [css-typed-om-1].
- A non-integer in a calc() automatically rounds to the nearest integer when used where an <integer> is required.
- Defined serialization of math functions.
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 constitutate a new privacy risk.