Skip to content
Permalink
master
Go to file
 
 
Cannot retrieve contributors at this time
4760 lines (3940 sloc) 178 KB
<pre class='metadata'>
Title: CSS Values and Units Module Level 4
Group: CSSWG
Shortname: css-values
Level: 4
Status: ED
Work Status: Exploring
ED: https://drafts.csswg.org/css-values-4/
TR: https://www.w3.org/TR/css-values-4/
Previous Version: https://www.w3.org/TR/2020/WD-css-values-4-20201111/
Previous Version: https://www.w3.org/TR/2019/WD-css-values-4-20190131/
Previous Version: https://www.w3.org/TR/2018/WD-css-values-4-20181010/
Editor: Tab Atkins, Google, http://xanthir.com/contact/, w3cid 42199
Editor: fantasai, http://fantasai.inkedblade.net/contact, w3cid 35400
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.
At Risk: ''toggle()'', ''attr()''
Ignored Terms: <spacing-limit>, containing block, property
Ignored Vars: Cn+1, n
Inline Github Issues: title
Default Highlight: css
</pre>
<pre class='link-defaults'>
spec: css-backgrounds-3; type: type; text: <position>
spec: css2; type: property; text: border-collapse
spec: css-color-4; type: value; text: currentcolor
spec: css-sizing-3; type: property;
text: min-width
text: box-sizing
spec: selectors-4; type: type; text: <wq-name>
spec: infra; type: dfn; text: string;
</pre>
<style>
code, small { white-space: nowrap }
pre.value { font: inherit; white-space: pre-wrap; margin: 0; padding: 0; }
#propvalues td { text-align: right; }
#propvalues td + td { text-align: left; }
dt + dt::before { content: ", "; }
dl:not(.switch) dt { display: inline; }
td > small { display: block; }
</style>
<h2 id="intro">
Introduction</h2>
The value definition field of each CSS property can contain keywords,
data types (which appear between <css>&lt;</css> and <css>></css>),
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.
<h3 id="placement">
Module Interactions</h3>
This module replaces and extends the data type definitions in [[!CSS21]]
sections
<a href="https://www.w3.org/TR/CSS21/about.html#value-defs">1.4.2.1</a>,
<a href="https://www.w3.org/TR/CSS21/syndata.html#values">4.3</a>,
and <a href="https://www.w3.org/TR/CSS21/aural.html#aural-intro">A.2</a>.
<!--
██████ ██ ██ ██ ██ ████████ ███ ██ ██
██ ██ ██ ██ ███ ██ ██ ██ ██ ██ ██
██ ████ ████ ██ ██ ██ ██ ██ ██
██████ ██ ██ ██ ██ ██ ██ ██ ███
██ ██ ██ ████ ██ █████████ ██ ██
██ ██ ██ ██ ███ ██ ██ ██ ██ ██
██████ ██ ██ ██ ██ ██ ██ ██ ██
-->
<h2 id="value-defs">
Value Definition Syntax</h2>
The <dfn for=CSS export>value definition syntax</dfn> described here
is used to define the set of valid values for CSS properties
(and the valid syntax of many other parts of CSS).
A value so described can have one or more components.
<h3 id="component-types">
Component Value Types</h3>
Component value types are designated in several ways:
<ol>
<li>
<a href="#keywords">keyword</a> values (such as <css>auto</css>, ''disc'', etc.),
which appear literally, without quotes (e.g. <code>auto</code>)
<li>
basic data types, which appear between <css>&lt;</css> and <css>></css>
(e.g., <<length>>, <<percentage>>, etc.).
For <a>numeric data types</a>,
this type notation can annotate any range restrictions
using the [[#numeric-ranges|bracketed range notation]] described below.
<li>
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 <em>not</em> include <a href="#common-keywords">CSS-wide keywords</a> such as ''inherit'',
and also does not include any top-level <a href="#mult-comma">comma-separated-list multiplier</a>
(i.e. if a property named <css>pairing</css> is defined as <css>[ <<custom-ident>> <<integer>>? ]#</css>,
then <css>&lt;\'pairing'></css> is equivalent to <css>[ <<custom-ident>> <<integer>>? ]</css>,
not <css>[ <<custom-ident>> <<integer>>? ]#</css>).
<li>
non-terminals that do not share the same name as a property.
In this case, the non-terminal name appears between <css>&lt;</css> and <css>></css>,
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.
</ol>
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.
<strong><dfn lt="," id='comb-comma' export grammar>Commas</dfn> specified in the grammar are implicitly omissible</strong> 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:
<ul>
<li>
all items preceding the comma have been omitted
<li>
all items following the comma have been omitted
<li>
multiple commas would be adjacent (ignoring <a href="https://www.w3.org/TR/css-syntax/#whitespace">white space</a>/comments),
due to the items between the commas being omitted.
</ul>
<div class='example'>
For example, if a function can accept three arguments in order,
but all of them are optional,
the grammar can be written like:
<pre class='prod'>
example( first? , second? , third? )
</pre>
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.
</div>
All CSS properties also accept the <a href="#common-keywords">CSS-wide keyword values</a>
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 <code>&lt;color>{1,4} | inherit | initial | unset</code>
(even though it is listed as <code>&lt;color>{1,4}</code>).
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.
<h3 id="component-combinators">
Component Value Combinators</h3>
Component values can be arranged into property values as follows:
<ul export dfn-type="grammar">
<li>Juxtaposing components means that
all of them must occur, in the given order.
<li>A double ampersand (<dfn id='comb-all'>&&</dfn>) separates two or more components,
all of which must occur, in any order.
<li>A double bar (<dfn id='comb-any'>||</dfn>) separates two or more options:
one or more of them must occur, in any order.
<li>A bar (<dfn id='comb-one'>|</dfn>) separates two or more alternatives:
exactly one of them must occur.
<li>Brackets ([&nbsp;]) are for grouping.
</ul>
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:
<pre>
a b | c || d && e f
[ a b ] | [ c || [ d && [ e f ]]]
</pre>
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:
<pre>
a || b || c
b || a || c
</pre>
<h3 id="component-multipliers">
Component Value Multipliers</h3>
Every type, keyword, or bracketed group may be followed by one of
the following modifiers:
<ul export dfn-type="grammar">
<li>An asterisk (<dfn id='mult-zero-plus'>*</dfn>) indicates that the preceding type, word, or
group occurs zero or more times.
<li>A plus (<dfn id='mult-one-plus'>+</dfn>) indicates that the preceding type, word, or group
occurs one or more times.
<li>A question mark (<dfn id='mult-opt'>?</dfn>) indicates that the preceding type, word, or
group is optional (occurs zero or one times).
<li>A single number in curly braces (<dfn id='mult-num'>{<var>A</var>}</dfn>)
indicates that the preceding type, word, or group occurs <var>A</var> times.
<li>A comma-separated pair of numbers in curly braces (<dfn id='mult-num-range'>{<var>A</var>,<var>B</var>}</dfn>)
indicates that the preceding type, word, or group occurs at least
<var>A</var> and at most <var>B</var> times.
The <var>B</var> may be omitted ({<var>A</var>,})
to indicate that there must be at least <var>A</var> repetitions,
with no upper bound on the number of repetitions.
<li>A hash mark (<dfn id='mult-comma'>#</dfn>) indicates that the preceding type, word, or
group occurs one or more times, separated by comma tokens
(which may optionally be surrounded by <a href="https://www.w3.org/TR/css-syntax/#whitespace">white space</a> and/or comments).
It may optionally be followed by the curly brace forms, above,
to indicate precisely how many times the repetition occurs,
like ''&lt;length>#{1,4}''.
<li>An exclamation point (<dfn id='mult-req'>!</dfn>) 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.
</ul>
For repeated component values (indicated by <css>*</css>, <css>+</css>, or <css>#</css>),
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.
<h3 id='combinator-multiplier-patterns'>
Combinator and Multiplier Patterns</h3>
There are a small set of common ways to combine multiple independent <a>component values</a> 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 <a href="#component-combinators">combinators</a> and <a href="#component-multipliers">multipliers</a>:
<table class='data'>
<thead>
<tr>
<th>
<th>in order
<th>any order
<tbody>
<tr>
<th>zero or more
<td><code>A? B? C?</code>
<td><code>A? || B? || C?</code>
<tr>
<th>one or more
<td><code>[ A? B? C? ]!</code>
<td><code>A || B || C</code>
<tr>
<th>all
<td><code>A B C </code>
<td><code>A && B && C</code>
</table>
Note that all of the "any order" possibilities are expressed using combinators,
while the "in order" possibilities are all variants on juxtaposition.
<h3 id="component-whitespace">
Component Values and White Space</h3>
Unless otherwise specified,
<a href="https://www.w3.org/TR/css-syntax/#whitespace">white space</a> and/or comments may appear before, after, and/or between
components combined using the above
<a href="#component-combinators">combinators</a> and
<a href="#component-multipliers">multipliers</a>.
Note: In many cases, spaces will in fact be <em>required</em> 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''.
<h3 id="value-examples">
Property Value Examples</h3>
Below are some examples of properties with their corresponding value
definition fields
<div class=example>
<table class="data" id="propvalues">
<thead>
<tr><th>Property
<th>Value definition field
<th>Example value
</thead>
<tbody>
<tr><td>'orphans'
<td>&lt;integer>
<td>''3''
<tr><td>'text-align'
<td>left | right | center | justify
<td>''text-align/center''
<tr><td>'padding-top'
<td>&lt;length> | &lt;percentage>
<td>''5%''
<tr><td>'outline-color'
<td>&lt;color> | invert
<td>''#fefefe''
<tr><td>'text-decoration'
<td>none | underline || overline || line-through || blink
<td>''overline underline''
<tr><td><a property>font-family</a>
<td>[ &lt;family-name> | &lt;generic-family> ]#
<td>''"Gill Sans", Futura, sans-serif''
<tr><td>'border-width'
<td>[ &lt;length> | thick | medium | thin ]{1,4}
<td>''2px medium 4px''
<tr><td>'box-shadow'
<td>[ inset? && &lt;length>{2,4} && &lt;color>? ]# | none
<td>''3px 3px rgba(50%, 50%, 50%, 50%), lemonchiffon 0 0 4px inset''
</tbody>
</table>
</div>
<h2 id="combining-values">
Combining Values: Interpolation, Addition, and Accumulation</h2>
Some procedures, for example
<a href="https://www.w3.org/TR/css-transitions/">transitions</a>
and <a href="https://www.w3.org/TR/css-animations/">animations</a>,
<dfn export>combine</dfn> two CSS property values.
The following combining operations--
on the two <a>computed values</a> <var>V<sub>a</sub></var> and <var>V<sub>B</sub></var>
yielding the <a>computed value</a> <var>V<sub>result</sub></var>--
are defined:
<dl export>
<dt><dfn id="interpolation" lt="interpolation | interpolate | value interpolation | interpolation procedure">interpolation</dfn>
<dd>
Given two property values
<var>V<sub>a</sub></var> and <var>V<sub>B</sub></var>,
produces an intermediate value
<var>V<sub>result</sub></var>
at a distance of <var>p</var>
along the interval between
<var>V<sub>a</sub></var> and <var>V<sub>B</sub></var>
such that <var>p</var> = 0 produces <var>V<sub>a</sub></var>
and <var>p</var> = 1 produces <var>V</var><sub>B</sub>.
The range of <var>p</var> is (&minus;&infin;, &infin;)
due to the effect of <a>timing functions</a>.
As a result, this procedure must also define
extrapolation behavior for <var>p</var> outside [0, 1].
<dt><dfn id="addition" lt="value addition | addition procedure" local-lt="add | addition">addition</dfn>
<dd>
Given two property values
<var>V<sub>a</sub></var> and <var>V<sub>B</sub></var>,
returns the sum of the two properties,
<var>V</var><sub>result</sub>.
For addition that is not commutative
(for example, matrix multiplication)
<var>V<sub>a</sub></var> represents
the first term of the operation and
<var>V<sub>B</sub></var> represents
the second.
Note: While <a>addition</a>
can often be expressed
in terms of the same weighted sum function
used to define <a>interpolation</a>,
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.
<dt><dfn id="accumulation" lt="value accumulation | accumulation procedure" local-lt="accumulate | accumulation">accumulation</dfn>
<dd>
Given two property values
<var>V<sub>a</sub></var> and <var>V<sub>B</sub></var>,
returns the result, <var>V<sub>result</sub></var>,
of combining the two operands
such that <var>V<sub>B</sub></var>
is treated as a <em>delta</em> from <var>V<sub>a</sub></var>.
For accumulation that is not commutative
(for example, accumulation of mismatched transform lists)
<var>V<sub>a</sub></var> represents the first term of the operation
and <var>V<sub>B</sub></var> represents the second.
<div class="note">
Note: For many types of animation such as numbers or lengths,
<a>accumulation</a> is defined to be identical
to <a>addition</a>.
A common case where the definitions differ
is for list-based types
where <a>addition</a> may be defined as appending to a list
whilst <a>accumulation</a> may be defined
as component-based addition.
For example, the filter list values ''blur(2)'' and ''blur(3)'',
when <a>added</a> together would produce ''blur(2) blur(3)'',
but when <a>accumulated</a> would produce ''blur(5)''.
</div>
</dl>
These operations are only defined on <a>computed values</a>.
(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 <a>canonical unit</a>
before being passed to any of the above procedures.)
If a value type does not define a specific procedure for <a>addition</a>
or is defined as <dfn export>not additive</dfn>,
its <a>addition</a> operation is simply
<var>V<sub>result</sub></var> = <var>V<sub>a</sub></var>.
If a value type does not define a specific procedure for <a>accumulation</a>,
its <a>accumulation</a> operation is identical to <a>addition</a>.
<h2 id="textual-values">
Textual Data Types</h2>
The <dfn export for=CSS>textual data types</dfn> include
various keywords and identifiers
as well as strings (<<string>>) and URLs (<<url>>).
Aside from the casing of <a href="#keywords">pre-defined keywords</a>
or as explicitly defined for a given property,
no normalization is performed,
not even Unicode normalization:
the <a lt="specified value">specified</a> and <a>computed value</a> of a property
are exactly the provided Unicode values after parsing
(which includes character set conversion and [[css-syntax-3#escaping|escaping]]).
[[!UNICODE]] [[!CSS-SYNTAX-3]]
CSS <dfn export lt="CSS identifier | CSS ident | identifier | ident">identifiers</dfn>,
generically denoted by <dfn>&lt;ident></dfn>,
consist of a sequence of characters conforming to the <<ident-token>> grammar. [[!CSS-SYNTAX-3]]
Identifiers cannot be quoted;
otherwise they would be interpreted as strings.
CSS properties accept two classes of <a>identifiers</a>:
[[#keywords|pre-defined keywords]]
and [[#custom-idents|author-defined identifiers]].
Note: The <<ident>> production is not meant for property value definitions--
<<custom-ident>> should be used instead.
It is provided as a convenience for defining other syntactic constructs.
All textual data types <a>interpolate</a> as <a>discrete</a>
and are <a>not additive</a>.
<!--
██ ██ ████████ ██ ██ ██ ██ ███████ ████████ ████████ ██████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
█████ ██████ ██ ██ ██ ██ ██ ██ ████████ ██ ██ ██████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ████████ ██ ███ ███ ███████ ██ ██ ████████ ██████
-->
<h3 id="keywords">
Pre-defined Keywords</h3>
In the value definition fields,
<dfn lt="keyword" export for=CSS>keywords</dfn> with a pre-defined meaning appear literally.
Keywords are <a>CSS identifiers</a>
and are interpreted <a lt="ASCII case-insensitive">ASCII case-insensitively</a>
(i.e., [a-z] and \[A-Z] are equivalent).
<div class="example">
For example, here is the value definition for the 'border-collapse'
property:
<pre>Value: collapse | separate</pre>
And here is an example of its use:
<pre>table { border-collapse: separate }</pre>
</div>
<h4 id="common-keywords">
CSS-wide keywords: ''initial'', ''inherit'' and ''unset''</h4>
As defined <a href="#component-types">above</a>,
all properties accept the <dfn export>CSS-wide keywords</dfn>,
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]]
<wpt>
css/css-values/initial-background-color.html
css/css-multicol/multicol-inherit-002.xht
css/css-multicol/multicol-rule-color-inherit-001.xht
css/css-multicol/multicol-rule-color-inherit-002.xht
css/css-values/unset-value-storage.html
css/CSS2/values/units-008.xht
</wpt>
Other CSS specifications can define additional CSS-wide keywords.
<!-- Make it easier to add CSS-wide keywords by defining a grammar production. -->
<h3 id='custom-idents'>
Author-defined Identifiers: the <<custom-ident>> type</h3>
Some properties accept arbitrary author-defined identifiers as a component value.
This generic data type is denoted by <dfn id="identifier-value">&lt;custom-ident></dfn>,
and represents any valid CSS <a>identifier</a>
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 using the "[=identical to=]" operation),
even in the ASCII range
(e.g. ''example'' and ''EXAMPLE'' are two different, unrelated user-defined identifiers).
The <a>CSS-wide keywords</a> 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--
for example by saying that any pre-defined keywords in that property's value definition are excluded.
Excluded keywords are excluded in all <a lt="ASCII case-insensitive">ASCII case permutations</a>.
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.
<div class="example">
For example, the shorthand declaration ''animation: ease-in ease-out''
is equivalent to the longhand declarations
''animation-timing-function: ease-in; animation-name: ease-out;''.
''ease-in'' is claimed by the <<easing-function>> production belonging to 'animation-timing-function',
leaving ''ease-out'' to be claimed by the <<custom-ident>> production belonging to 'animation-name'.
</div>
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.
<h3 id='dashed-idents'>
<em>Explicitly</em> Author-defined Identifiers: the <<dashed-ident>> type</h3>
Some contexts accept <em>both</em> author-defined identifiers
<em>and</em> CSS-defined identifiers.
If not handled carefully,
this can result in difficulties adding new CSS-defined values;
UAs have to study existing usage
and gamble that there are sufficiently few author-defined identifiers in use
matching the new CSS-defined one,
so giving the new value a special CSS-defined meaning
won't break existing pages.
While there are many legacy cases in CSS
that mix these two values spaces in exactly this fraught way,
the <<dashed-ident>> type is meant to be an easy way
to distinguish author-defined identifiers
from CSS-defined identifiers.
The <dfn><<dashed-ident>></dfn> production
is a <<custom-ident>>,
with all the case-sensitivity that implies,
with the additional restriction that it must start with two dashes
(U+002D HYPHEN-MINUS).
<<dashed-ident>>s are reserved solely for use as author-defined names.
CSS will never define a <<dashed-ident>> for its own use.
<div class=example>
For example, [=custom properties=] need to be distinguishable from CSS-defined properties,
as new properties are added to CSS regularly.
To allow this,
[=custom property=] names are required to be <<dashed-ident>>s,
as in this example:
<pre highlight=css>
.foo {
--fg-color: blue;
}
</pre>
</div>
<div class=example>
<<dashed-ident>>s are also used in the ''@color-profile'' rule,
to separate author-defined color profiles
from pre-defined ones like ''device-cmyk'',
and allow CSS to define more pre-defined (but overridable) profiles in the future
without fear of clashing with author-defined profiles:
<pre highlight=css>
@color-profile --foo { src: url(https://example.com/foo.icc); }
.foo {
color: color(--foo 1 0 .5 / .2);
}
</pre>
</div>
<div class=example>
CSS will use <<dashed-ident>> more in the future,
as more author-controlled syntax is added.
CSS authoring tools,
such as preprocessors that turn custom syntax into standard CSS,
<em>should</em> use <<dashed-ident>> as well,
to avoid clashing with future CSS design.
For example,
if a CSS preprocessor added a new "custom" at-rule,
it <em>shouldn't</em> spell it <css>@custom</css>,
as this would clash with a future official <css>@custom</css> rule added by CSS.
Instead, it should use <css>@--custom</css>,
which is guaranteed to never clash with anything defined by CSS.
Even better, it should use <css>@--library1-custom</css>,
so that if Library2 adds their own "custom" at-rule
(spelled @--library2-custom),
there's no possibility of clash.
Ideally this prefix should be customizable,
if allowed by the tooling,
so authors can manually avoid clashes on their own.
</div>
<!--
██████ ████████ ████████ ████ ██ ██ ██████
██ ██ ██ ██ ██ ██ ███ ██ ██ ██
██ ██ ██ ██ ██ ████ ██ ██
██████ ██ ████████ ██ ██ ██ ██ ██ ████
██ ██ ██ ██ ██ ██ ████ ██ ██
██ ██ ██ ██ ██ ██ ██ ███ ██ ██
██████ ██ ██ ██ ████ ██ ██ ██████
-->
<h3 id="strings">
Quoted Strings: the <<string>> type</h3>
[=Strings=] are denoted by <dfn id="string-value">&lt;string></dfn>
and consist of a sequence of characters delimited by double quotes or
single quotes. They correspond to the <<string-token>> production
in the <a href="https://www.w3.org/TR/css-syntax/">CSS Syntax Module</a> [[!CSS-SYNTAX-3]].
<div class=example>
Double quotes cannot occur inside double quotes, unless
<a href="https://www.w3.org/TR/CSS21/syndata.html#escaped-characters">escaped</a>
(as <code>"\""</code> or as <code>"\22"</code>).
Analogously for single quotes (<code>&#39;\&#39;&#39;</code> or <code>&#39;\27&#39;</code>).
<pre>
content: "this is a &#39;string&#39;.";
content: "this is a \"string\".";
content: &#39;this is a "string".&#39;;
content: &#39;this is a \&#39;string\&#39;.&#39;
</pre>
</div>
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:
<div class="example">
<p style="display:none">Example(s):
<pre>
a[title="a not s\
o very long title"] {/*...*/}
a[title="a not so very long title"] {/*...*/}
</pre>
</div>
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.)
<!--
██ ██ ████████ ██
██ ██ ██ ██ ██
██ ██ ██ ██ ██
██ ██ ████████ ██
██ ██ ██ ██ ██
██ ██ ██ ██ ██
███████ ██ ██ ████████
-->
<h3 id="urls">
Resource Locators: the <<url>> type</h3>
The <<url>> type
represents a <l spec=url>[=/URL=]</l>,
which is a pointer to a resource.
Typically, a <<url>> is written with the <dfn>url()</dfn>
or <dfn>src()</dfn> <a>functional notations</a>:
<pre class="prod">
<dfn id="url-value">&lt;url></dfn> = url( <<string>> <<url-modifier>>* ) |
src( <<string>> <<url-modifier>>* )
</pre>
<div class="example">
This example shows a URL being used as a background image:
<pre highlight=css>
body { background: url("http://www.example.com/pinkish.gif") }
</pre>
</div>
For legacy reasons, a ''url()'' can be written without quotation marks around the URL itself,
in which case it is <a lt="consume a url token" spec=css-syntax-3>specially-parsed</a>
as a <<url-token>> [[!CSS-SYNTAX-3]].
Because of this special parsing, ''url()'' is only able to specify its URL literally;
''src()'' lacks this special parsing rule,
and so its URL can be provided by functions,
such as ''var()''.
<div class="example">
For example, the following declarations are identical:
<pre>
background: url("http://www.example.com/pinkish.gif");
background: url(http://www.example.com/pinkish.gif);
</pre>
And these have the same meaning as well:
<pre>
background: src("http://www.example.com/pinkish.gif");
--foo: "http://www.example.com/pinkish.gif";
background: src(var(--foo));
</pre>
But this does <em>not</em> work:
<pre>
--foo: "http://www.example.com/pinkish.gif";
background: url(var(--foo));
</pre>
...because the unescaped "(" in the value causes a parse error,
so the entire declaration is thrown out as invalid.
</div>
<div class=note>
The unquoted ''url()'' syntax cannot accept a <<url-modifier>> argument
and has extra escaping requirements:
parentheses, <a href="https://www.w3.org/TR/css-syntax/#whitespace">whitespace</a> characters,
single quotes (&#39;) 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]].
The precise requirements for parsing the unquoted ''url()'' syntax
are normatively defined in [[!CSS-SYNTAX-3]].
</div>
Some CSS contexts (such as ''@import'') also allow a <<url>>
to be represented by a bare <<string>>, without the function wrapper.
In such cases the string behaves identically to a ''url()'' function containing that string.
<div class="example">
For example, the following statements act identically:
<pre>
@import url("base-theme.css");
@import "base-theme.css";
</pre>
</div>
<h4 id="relative-urls">
Relative URLs</h4>
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&nbsp;3986, section&nbsp;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.
Note: For HTML documents,
the <a href="https://html.spec.whatwg.org/multipage/urls-and-fetching.html#dynamic-changes-to-base-urls">base URL is mutable</a>.
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.
<div class="example">
For example, suppose the following rule:
<pre>body { background: url("tile.png") }</pre>
is located in a style sheet designated by the URL:
<pre>http://www.example.org/style/basic.css</pre>
The background of the source document's <code>&lt;body></code>
will be tiled with whatever image is described by the resource designated by the URL:
<pre>http://www.example.org/style/tile.png</pre>
The same image will be used regardless of the URL of the source document containing the <code>&lt;body></code>.
</div>
<h5 id='local-urls'>
Fragment URLs</h5>
To work around some common eccentricities in browser URL handling,
CSS has special behavior for fragment-only urls.
If a ''url()''’s value starts with a U+0023 NUMBER SIGN (<code>#</code>) character,
parse it as per normal for URLs,
but additionally set the <dfn export for="url()">local url flag</dfn> of the ''url()''.
When matching a ''url()'' with the <a>local url flag</a> 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 <a href="https://www.w3.org/TR/cssom-1/#serializing-css-values">serializing</a>
a ''url()'' with the <a>local url flag</a> set,
it must serialize as just the fragment.
<details class=note>
<summary>What “browser eccentricities”?</summary>
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 {{History/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.
</details>
<h4 id="url-empty">
Empty URLs</h4>
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 editing 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 <em>does</em> allow empty urls,
so if/when CSS gains some functionality to control hyperlinks,
this restriction can be relaxed in those contexts.
<h4 id='url-modifiers'>
URL Modifiers</h4>
The ''url()'' function supports specifying additional <dfn>&lt;url-modifier></dfn>s,
which change the meaning or the interpretation of the URL somehow.
A <<url-modifier>> is either an <<ident>> or a <a>functional notation</a>.
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.
<h2 id="numeric-types">
Numeric Data Types</h2>
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 <a lt="specified value">specified</a> and <a>computed value</a>
do not distinguish these variations:
they represent the value’s abstract quantity,
not its syntactic representation.
The <dfn>numeric data types</dfn> include
<<integer>>,
<<number>>,
<<percentage>>,
and various <a>dimensions</a>
including <<length>>, <<angle>>, <<time>>, <<frequency>>, and <<resolution>>.
Note: While general-purpose <a>dimensions</a> are defined here,
some other modules define additional data types
(e.g. [[css-grid-1]] introduces ''fr'' units)
whose usage is more localized.
The precision and supported range of numeric values in CSS
is <em>explicitly undefined</em>,
and can vary based on the property or other context a value is used in.
However, within the CSS specifications,
infinite precision and range is assumed.
When a value cannot be explicitly supported due to range/precision limitations,
it must be converted to the closest value supported by the implementation,
but how the implementation defines "closest" is explicitly undefined as well.
<h3 id="numeric-ranges">
Range Restrictions and Range Definition Notation</h3>
Properties can restrict numeric values to some range.
If the value is outside the allowed range,
then unless otherwise specified,
the declaration is invalid and must be <a href="https://www.w3.org/TR/CSS21/conform.html#ignore">ignored</a>.
Range restrictions can be annotated in the numeric type notation
using <dfn export local-lt="bracketed range notation">CSS bracketed range notation</dfn>--
<code>[<var>min</var>,<var>max</var>]</code>--
within the angle brackets, after the identifying keyword,
indicating a closed range
between (and including) <var>min</var> and <var>max</var>.
For example, <<integer [0,10]>> indicates an integer between ''0'' and ''10'', inclusive.
Note: CSS values generally do not allow open ranges;
thus only square-bracket notation is used.
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.
Range extremes that are ideally unlimited
are indicated using &infin; or &minus;&infin; as appropriate.
For example, <<length [0, &infin;]>> indicates a non-negative length.
If no range is indicated,
either by using the <a>bracketed range notation</a>
or in the property description,
then <code>[&minus;&infin;,&infin;]</code> is assumed.
Note: At the time of writing,
the <a>bracketed range notation</a> is new;
thus in most CSS specifications
any range limitations are described only in prose.
(For example, “Negative values are not allowed” or
“Negative values are invalid”
indicate a <code>[0,&infin;]</code> range.)
This does not make them any less binding.
<!--
The recommended minimum ranges and precision,
and the required rounding and clamping rules,
are given in <a href="#required-ranges">Appendix A</a>.
-->
<!--
████ ██ ██ ████████ ████████ ██████ ████████ ████████
██ ███ ██ ██ ██ ██ ██ ██ ██ ██
██ ████ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██████ ██ ████ ██████ ████████
██ ██ ████ ██ ██ ██ ██ ██ ██ ██
██ ██ ███ ██ ██ ██ ██ ██ ██ ██
████ ██ ██ ██ ████████ ██████ ████████ ██ ██
-->
<h3 id="integers">
Integers: the <<integer>> type</h3>
Integer values are denoted by <dfn id="integer-value">&lt;integer></dfn>.
When written literally,
an <dfn export>integer</dfn> is one or more decimal digits ''0'' through ''9''
and corresponds to a subset of the <<number-token>> production
in the CSS Syntax Module [[!CSS-SYNTAX-3]].
The first digit of an integer may be immediately preceded by <css>-</css> or <css>+</css>
to indicate the integer's sign.
<wpt>
css/css-multicol/multicol-count-non-integer-001.xht
css/css-multicol/multicol-count-non-integer-002.xht
css/css-multicol/multicol-count-non-integer-003.xht
css/CSS2/values/numbers-units-001.xht
css/CSS2/values/numbers-units-004.xht
</wpt>
<h4 id="combine-integers">
Combination of <<integer>></h4>
<a>Interpolation</a> of <<integer>> is defined as
<var>V</var><sub>result</sub> =
round((1 - <var>p</var>) &times; <var>V<sub>a</sub></var> +
<var>p</var> &times; <var>V<sub>b</sub></var>);
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.
<a>Addition</a> of <<integer>> is defined as
<var>V<sub>result</sub></var> =
<var>V<sub>a</sub></var> + <var>V<sub>b</sub></var>
<wpt>
css/css-values/calc-positive-fraction-001.html
css/css-values/rgba-011.html
</wpt>
<!--
██ ██ ██ ██ ██ ██ ████████ ████████ ████████
███ ██ ██ ██ ███ ███ ██ ██ ██ ██ ██
████ ██ ██ ██ ████ ████ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ███ ██ ████████ ██████ ████████
██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ███████ ██ ██ ████████ ████████ ██ ██
-->
<h3 id="numbers">
Real Numbers: the <<number>> type</h3>
Number values are denoted by <dfn id="number-value">&lt;number></dfn>,
and represent real numbers, possibly with a fractional component.
<wpt>
css/css-animations/animation-iteration-count-calc.html
css/CSS2/values/numbers-units-002.xht
css/CSS2/values/numbers-units-003.xht
</wpt>
When written literally,
a <dfn export>number</dfn> is either an <a>integer</a>,
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 <a href="https://www.w3.org/TR/css-syntax/">CSS Syntax Module</a> [[!CSS-SYNTAX-3]].
As with integers, the first character of a number
may be immediately preceded by <css>-</css> or <css>+</css>
to indicate the number's sign.
The value <dfn id=zero-value>&lt;zero></dfn> represents a literal <a>number</a>
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.
<h4 id="combine-numbers">
Combination of <<number>></h4>
<a>Interpolation</a> of <<number>> is defined as
<var>V</var><sub>result</sub> =
(1 - <var>p</var>) &times; <var>V<sub>a</sub></var> +
<var>p</var> &times; <var>V<sub>b</sub></var>
<a>Addition</a> of <<number>> is defined as
<var>V<sub>result</sub></var> =
<var>V<sub>a</sub></var> + <var>V<sub>b</sub></var>
<h3 id='dimensions'>
Numbers with Units: <a>dimension</a> values</h3>
The general term <dfn export>dimension</dfn> refers to
a number with a unit attached to it;
and is denoted by <dfn>&lt;dimension></dfn>.
When written literally,
a <a>dimension</a> is a <a>number</a>
immediately followed by a unit identifier,
which is an <a>identifier</a>.
It corresponds to the <<dimension-token>> production
in the <a href="https://www.w3.org/TR/css-syntax/">CSS Syntax Module</a> [[!CSS-SYNTAX-3]].
Like keywords, unit identifiers are <a>ASCII case-insensitive</a>.
<wpt>
css/css-values/angle-units-003.html
</wpt>
CSS uses <<dimension>>s to specify
distances (<<length>>),
durations (<<time>>),
frequencies (<<frequency>>),
resolutions (<<resolution>>),
and other quantities.
<h4 id="compat">
Compatible Units</h4>
When <a href="https://www.w3.org/TR/cssom-1/#serializing-css-values">serializing</a> <a>computed values</a> [[!CSSOM]],
<dfn export local-lt=compatible>compatible units</dfn>
(those related by a static multiplicative factor,
like the 96:1 factor between ''px'' and ''in'',
or the computed 'font-size' factor between ''em'' and ''px'')
are converted into a single <dfn export local-lt=canonical>canonical unit</dfn>.
Each group of compatible units defines which among them is the <a>canonical unit</a>
that will be used for serialization.
When serializing <a href="https://www.w3.org/TR/cssom-1/#resolved-values">resolved values</a>
that are <a>used values</a>,
all value types (percentages, numbers, keywords, etc.)
that represent lengths are considered <a>compatible</a> with lengths.
Likewise any future API that returns <a>used values</a>
must consider any values that represent distances/durations/frequencies/etc.
as <a>compatible</a> with the relevant class of <a>dimensions</a>,
and canonicalize accordingly.
<wpt>
css/css-values/calc-serialization-002.html
</wpt>
<h4 id="combine-dimensions">
Combination of Dimensions</h4>
<a>Interpolation</a> of <a>compatible</a> <a>dimensions</a>
(for example, two <<length>> values)
is defined as
<var>V</var><sub>result</sub> =
(1 - <var>p</var>) &times; <var>V<sub>a</sub></var> +
<var>p</var> &times; <var>V<sub>b</sub></var>
<a>Addition</a> of <a>compatible</a> <a>dimensions</a> is defined as
<var>V<sub>result</sub></var> =
<var>V<sub>a</sub></var> + <var>V<sub>b</sub></var>
<!--
█████ ██
██ ██ ██
█████ ██
██
██ █████
██ ██ ██
██ █████
-->
<h3 id="percentages">
Percentages: the <<percentage>> type</h3>
Percentage values are denoted by <dfn id="percentage-value">&lt;percentage></dfn>,
and indicates a value that is some fraction of another reference value.
When written literally,
a <dfn export>percentage</dfn> consists of a <a>number</a>
immediately followed by a percent sign <css>%</css>.
It corresponds to the <<percentage-token>> production
in the <a href="https://www.w3.org/TR/css-syntax/">CSS Syntax Module</a> [[!CSS-SYNTAX-3]].
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 <a>containing block</a>),
or something else.
<wpt>
css/CSS2/values/numbers-units-016.xht
css/CSS2/values/numbers-units-017.xht
</wpt>
<h4 id="combine-percentages">
Combination of <<percentage>></h4>
<a>Interpolation</a> of <<percentage>> is defined as
<var>V</var><sub>result</sub> =
(1 - <var>p</var>) &times; <var>V<sub>a</sub></var> +
<var>p</var> &times; <var>V<sub>b</sub></var>
<a>Addition</a> of <<percentage>> is defined as
<var>V<sub>result</sub></var> =
<var>V<sub>a</sub></var> + <var>V<sub>b</sub></var>
<h3 id="mixed-percentages">
Mixing Percentages and Dimensions</h3>
In cases where a <<percentage>> can represent the same quantity
as a <a>dimension</a> in the same <a>component value</a> position,
and can therefore be combined with them in a ''calc()'' expression,
the following convenience notations may be used in the property grammar:
: <dfn>&lt;length-percentage></dfn>
:: Equivalent to <code class=prod>[ <<length>> | <<percentage>> ]</code>,
where the <<percentage>> will resolve to a <<length>>.
: <dfn>&lt;frequency-percentage></dfn>
:: Equivalent to <code class=prod>[ <<frequency>> | <<percentage>> ]</code>,
where the <<percentage>> will resolve to a <<frequency>>.
: <dfn>&lt;angle-percentage></dfn>
:: Equivalent to <code class=prod>[ <<angle>> | <<percentage>> ]</code>,
where the <<percentage>> will resolve to an <<angle>>.
: <dfn>&lt;time-percentage></dfn>
:: Equivalent to <code class=prod>[ <<time>> | <<percentage>> ]</code>,
where the <<percentage>> will resolve to a <<time>>.
<div class="example">
For example, the 'width' property can accept a <<length>> or a <<percentage>>,
both representing a measure of distance.
This means that ''width: calc(500px + 50%);'' is allowed--
both values are converted to absolute lengths and added.
If the containing block is ''1000px'' wide,
then ''width: 50%;'' is equivalent to ''width: 500px'',
and ''width: calc(50% + 500px)'' thus ends up equivalent to ''width: calc(500px + 500px)'' or ''width: 1000px''.
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%)''.
</div>
Note: Specifications should never alternate <<percentage>> in place of a dimension
in a grammar unless they are <a>compatible</a>.
Note: More &lt;<var ignore>type</var>-percentage> productions can be added in the future as needed.
A &lt;number-percentage> will never be added,
as <<number>> and <<percentage>> can't be combined in ''calc()''.
<h4 id="combine-mixed">
Combination of Percentage and Dimension Mixes</h4>
<a>Interpolation</a> of percengage-dimension value combinations
(e.g. <<length-percentage>>, <<frequency-percentage>>, <<angle-percentage>>, <<time-percentage>>
or equivalent notations)
is defined as
<ul>
<li>
equivalent to <a>interpolation</a> of <<length>>
if both <var>V<sub>a</sub></var> and <var>V<sub>b</sub></var> are pure <<length>> values
<li>
equivalent to <a>interpolation</a> of <<percentage>>
if both <var>V<sub>a</sub></var> and <var>V<sub>b</sub></var> are pure <<percentage>> values
<li>
equivalent to converting both values into a ''calc()'' expression
representing the sum of the dimension type and a percentage
(each possibly zero)
and <a>interpolating</a> each component individually
(as a <<length>>/<<frequency>>/<<angle>>/<<time>>
and as a <<percentage>>, respectively)
</ul>
<a>Addition</a> of <<percentage>> is defined
the same as <a>interpolation</a>
except by <a>adding</a> each component
rather than <a>interpolating</a> it.
<h3 id='ratios'>
Ratios: the <<ratio>> type</h3>
Ratio values are denoted by <dfn id=ratio-value>&lt;ratio></dfn>,
and represent the ratio of two numeric values.
It most often represents an aspect ratio,
relating a width (first) to a height (second).
When written literally,
a <dfn export>ratio</dfn> has the syntax:
<pre class=prod>
<<ratio>> = <<number [0,Infinity]>> [ / <<number [0,Infinity]>> ]?
</pre>
The second <<number>> is optional,
defaulting to ''1''.
However, <<ratio>> is always serialized with both components.
The computed value of a <<ratio>> is the pair of numbers provided.
If either number in the <<ratio>> is 0 or infinite,
it represents a <dfn export>degenerate ratio</dfn>
(and, generally, won't do anything).
If two <<ratio>>s need to be compared,
divide the first number by the second,
and compare the results.
For example, <css>3/2</css> is less than <css>2/1</css>,
because it resolves to 1.5 while the second resolves to 2.
(In other words, “tall” aspect ratios are less than “wide” aspect ratios.)
<h4 id='combine-ratio'>
Combination of <<ratio>></h4>
The interpolation of a <<ratio>> is defined
by converting each <<ratio>> to a number
by dividing the first value by the second
(so a ratio of ''3 / 2'' would become ''1.5''),
taking the logarithm of that result
(so the ''1.5'' would become approximately ''0.176''),
then interpolating those values.
The result during the interpolation
is converted back to a <<ratio>>
by inverting the logarithm,
then interpreting the result as a <<ratio>>
with the result as the first value and ''1'' as the second value.
If either <<ratio>> is [=degenerate ratio|degenerate=],
the values cannot be interpolated.
<div class='example'>
For example,
halfway through a linear interpolation from ''5 / 1'' to ''3 / 2'',
the result is approximately the ratio ''2.73 / 1''
(roughly ''11 / 4'', slightly taller than a ''3 / 1'' ratio):
<pre>
start = log(5); // ≈ 0.69897
end = log(1.5); // ≈ 0.17609
interp = 0.69897*.5 + 0.17609*.5; // ≈ 0.43753
final = 10^interp; // ≈ 2.73
</pre>
</div>
Note: Interpolating over the logarithm of the ratio
means the results are scale-independent
(''5 / 1'' to ''300 / 200'' would give the same results as above),
that they're symmetrical over "wide" and "tall" variants
(interpolating from ''1 / 5'' to ''2 / 3'' would give
a ratio approximately equal to ''1 / 2.73'' at the halfway point),
and that they're symmetrical over whether the width is fixed and the height is based on the ratio
or vice versa.
These properties are not shared by many other possible interpolation strategies.
Note: Due to the properties of logarithms,
any log can be used;
the example here uses base-10 log,
but if, say, the natural log and e was used,
the intermediate results would be different
but the final result would be the same.
Addition of <<ratio>>s is not possible.
<!--
██ ████████ ██ ██ ██████ ████████ ██ ██
██ ██ ███ ██ ██ ██ ██ ██ ██
██ ██ ████ ██ ██ ██ ██ ██
██ ██████ ██ ██ ██ ██ ████ ██ █████████
██ ██ ██ ████ ██ ██ ██ ██ ██
██ ██ ██ ███ ██ ██ ██ ██ ██
████████ ████████ ██ ██ ██████ ██ ██ ██
-->
<h2 id="lengths">
Distance Units: the <<length>> type</h2>
Lengths refer to distance measurements
and are denoted by <dfn id="length-value">&lt;length></dfn> in the property definitions.
A length is a <a>dimension</a>.
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 <a href="https://www.w3.org/TR/CSS21/conform.html#ignore">ignored</a>.
<wpt>
css/mediaqueries/min-width-001.xht
css/CSS2/values/numbers-units-005.xht
css/CSS2/values/numbers-units-006.xht
</wpt>
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 <a lt="used value">used</a> length cannot be supported,
user agents must approximate it in the <a lt="actual value">actual</a> value.
There are two types of length units: <a lt="relative length">relative</a> and <a lt="absolute length">absolute</a>.
<wpt>
css/css-values/calc-unit-analysis.html
css/css-shapes/shape-outside/values/shape-outside-circle-002.html
css/css-shapes/shape-outside/values/shape-outside-circle-004.html
css/css-shapes/shape-outside/values/shape-outside-ellipse-002.html
css/css-shapes/shape-outside/values/shape-outside-ellipse-004.html
css/css-shapes/shape-outside/values/shape-outside-inset-003.html
css/css-shapes/shape-outside/values/shape-outside-polygon-004.html
</wpt>
<h3 id="relative-lengths">
Relative Lengths</h3>
<dfn lt="relative length">Relative length units</dfn> 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:
<table class="data">
<caption>Informative Summary of Relative Units</caption>
<thead>
<tr><th>unit<th>relative to
</thead>
<tbody>
<tr><td>''em''
<td>font size of the element
<tr><td>''ex''
<td>x-height of the element's font
<tr><td>''cap''
<td>cap height (the nominal height of capital letters) of the element's font
<tr><td>''ch''
<td>typical <a lt="advance measure">character advance</a>
of a narrow glyph in the element’s font,
as represented by the “0” (ZERO, U+0030) glyph
<tr><td>''ic''
<td>typical <a lt="advance measure">character advance</a>
of a fullwidth glyph in the element’s font,
as represented by the “水” (CJK water ideograph, U+6C34) glyph
<tr><td>''rem''
<td>font size of the root element
<tr><td>''lh''
<td>line height of the element
<tr><td>''rlh''
<td>line height of the root element
<tr><td>''vw''
<td>1% of viewport's width
<tr><td>''vh''
<td>1% of viewport's height
<tr><td>''vi''
<td>1% of viewport's size in the root element's <a>inline axis</a>
<tr><td>''vb''
<td>1% of viewport's size in the root element's <a>block axis</a>
<tr><td>''vmin''
<td>1% of viewport's smaller dimension
<tr><td>''vmax''
<td>1% of viewport's larger dimension
</tbody>
</table>
Child elements do not inherit the relative values as specified for their parent;
they inherit the <a>computed values</a>.
<!--
████████ ██ ██ ██ ████████ ████████ ██████
██ ███ ███ ██ ██ ██ ██ ██
██ ████ ████ ██ ██ ██ ██
██████ ██ ███ ██ ██ ██████ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
████████ ██ ██ ██ ████████ ██ ██████
-->
<h4 id="font-relative-lengths">
Font-relative Lengths: the ''em'', ''ex'', ''cap'', ''ch'', ''ic'', ''rem'', ''lh'', ''rlh'' units</h4>
The <dfn export id="font-relative-length">font-relative lengths</dfn>
refer to the font metrics of the element on which they are used--
or, in the case of ''rem'' and ''rlh'', the metrics of the root element.
<figure>
<img src="images/Typography_Line_Terms.svg" alt="The word 'Sphinx' annotated with various font metrics: ascender height, to the top of the h's serif; cap height, to the visually approximate top of the S; the x height, to the visually approximate top of the x; the baseline, along the bottom of S, h, i, n, and x; and the descender height, to the bottom fo the p.">
<figcaption>
Common typographic metrics
</figcaption>
</figure>
<dl export dfn-type=value dfn-for="<length>">
<dt><dfn id="em" lt="em">em unit</dfn>
<dd>
Equal to the computed value of the 'font-size' property of the element on which it is used.
<div class="example">
The rule:
<pre>h1 { line-height: 1.2em }</pre>
means that the line height of <code>h1</code> elements
will be 20% greater than the font size of <code>h1</code> element.
On the other hand:
<pre>h1 { font-size: 1.2em }</pre>
means that the font size of <code>h1</code> elements
will be 20% greater than the computed font size inherited by <code>h1</code> elements.
</div>
<dt><dfn id="ex" lt="ex">ex unit</dfn>
<dd>
Equal to the used x-height of the <a href="https://www.w3.org/TR/css3-fonts/#first-available-font">first available font</a> [[!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.
<wpt>
css/css-values/ex-unit-001.html
css/css-values/ex-unit-002.html
css/css-values/ex-unit-003.html
css/CSS2/values/numbers-units-007.xht
css/CSS2/values/numbers-units-009.xht
css/CSS2/values/numbers-units-010.xht
css/CSS2/values/numbers-units-011.xht
css/CSS2/values/numbers-units-012.xht
css/CSS2/values/numbers-units-013.xht
css/CSS2/values/numbers-units-015.xht
css/CSS2/values/numbers-units-019.xht
css/CSS2/values/units-001.xht
css/CSS2/values/units-002.xht
css/CSS2/values/units-003.xht
css/CSS2/values/units-004.xht
css/CSS2/values/units-005.xht
css/css-values/calc-ch-ex-lang.html
</wpt>
<dt><dfn id="cap" lt="cap">cap unit</dfn>
<dd>
Equal to the used cap-height of the <a href="https://www.w3.org/TR/css3-fonts/#first-available-font">first available font</a> [[!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.
<dt><dfn id="ch" lt="ch">ch unit</dfn>
<dd>
Equal to the used <a>advance measure</a> of the “0” (ZERO, U+0030) glyph
in the font used to render it.
(The <dfn dfn>advance measure</dfn> of a glyph is its advance width or height,
whichever is in the inline axis of the element.)
Note: This measurement is an approximation
(and in monospace fonts, an exact measure)
of a single narrow glyph’s <a>advance measure</a>,
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 ''text-orientation/upright'').
<wpt>
css/css-values/ch-unit-001.html
css/css-values/ch-unit-002.html
css/css-values/ch-unit-003.html
css/css-values/ch-unit-004.html
css/css-values/ch-unit-008.html
css/css-values/ch-unit-009.html
css/css-values/ch-unit-010.html
css/css-values/ch-unit-011.html
css/css-values/ch-unit-012.html
css/css-values/ch-unit-016.html
css/css-values/ch-unit-017.html
css/css-values/line-break-ch-unit.html
css/css-values/calc-ch-ex-lang.html
</wpt>
<dt><dfn id="ic" lt="ic">ic unit</dfn>
<dd>
Equal to the used <a>advance measure</a> 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 <a href="http://unicode.org/reports/tr11/#Definitions">fullwidth</a> glyph’s <a>advance measure</a>,
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.
<wpt>
css/css-values/ic-unit-001.html
css/css-values/ic-unit-002.html
css/css-values/ic-unit-003.html
css/css-values/ic-unit-004.html
css/css-values/ic-unit-008.html
css/css-values/ic-unit-009.html
css/css-values/ic-unit-010.html
css/css-values/ic-unit-011.html
css/css-values/ic-unit-012.html
</wpt>
<dt><dfn id="rem" lt="rem">rem unit</dfn>
<dd>
Equal to the computed value of 'font-size' on the root element.
When specified in the 'font-size' property of the root element,
or in a document with no root element,
''1rem'' is equal to the initial value of the 'font-size' property.
<wpt>
css/css-values/calc-rem-lang.html
</wpt>
<dt><dfn id="lh" lt="lh">lh unit</dfn>
<dd>
Equal to the computed value of the 'line-height' property of the element on which it is used,
converting ''line-height/normal'' to an absolute length
by using only the metrics of the <a href="https://www.w3.org/TR/css3-fonts/#first-available-font">first available font</a>.
<wpt>
css/css-values/lh-rlh-on-root-001.html
css/css-values/lh-unit-001.html
css/css-values/lh-unit-002.html
</wpt>
<dt><dfn id="rlh" lt="rlh">rlh unit</dfn>
<dd>
Equal to the computed value of 'line-height' property on the root element,
converting ''line-height/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.
<wpt>
css/css-values/lh-rlh-on-root-001.html
</wpt>
</dl>
Issue: 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 <a>media queries</a>),
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--
or against the computed metrics corresponding to the initial values
of the 'font' and 'line-height' properties,
if the element has no parent.
Additionally,
when ''lh'' or ''rlh'' units are used
in the value of the 'line-height' property on the element they refer to,
they resolve against the computed 'line-height' and font metrics of the parent element--
or the computed metrics corresponding to the initial values
of the 'font' and 'line-height' properties,
if the element has no parent.
(The other font-relative units continue to resolve against
the element’s own metrics when used in 'line-height'.)
<!--
██ ██ ██ ██ ██ ████████ ████████ ██████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██████ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███ ███ ███ ██ ████████ ██ ██████
-->
<h4 id="viewport-relative-lengths">
Viewport-percentage Lengths: the ''vw'', ''vh'', ''vi'', ''vb'', ''vmin'', ''vmax'' units</h4>
The <dfn export>viewport-percentage lengths</dfn> are relative to the size of the
<a href="https://www.w3.org/TR/CSS21/visudet.html#containing-block-details">initial containing block</a>.
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 ''overflow/auto'',
any scroll bars are assumed not to exist.
<span class='note'>Note that the initial containing block's size is affected by the presence of scrollbars on the viewport.</span>
ISSUE(1766): Level 3 assumes scrollbars never exist because it was hard to implement. This is making authors unhappy.
For [=paged media=], the exact definition of the viewport-percentage lengths
is deferred to [[!CSS3PAGE]].
<dl export dfn-type=value dfn-for="<length>">
<dt><dfn id="vw" lt="vw">vw unit</dfn>
<dd>
Equal to 1% of the width of the initial containing block.
<div class="example">
In the example below, if the width of the viewport is 200mm,
the font size of <code>h1</code> elements will be 16mm
(i.e. (8×200mm)/100).
<pre>h1 { font-size: 8vw }</pre>
</div>
<dt><dfn id="vh" lt="vh">vh unit</dfn>
<dd>
Equal to 1% of the height of the initial containing block.
<dt><dfn lt=vi>vi unit</dfn>
<dd>
Equal to 1% of the size of the initial containing block
in the direction of the root element's inline axis.
<dt><dfn lt=vb>vb unit</dfn>
<dd>
Equal to 1% of the size of the initial containing block
in the direction of the root element's block axis.
<dt><dfn id="vmin" lt="vmin">vmin unit</dfn>
<dd>
Equal to the smaller of ''vw'' or ''vh''.
<dt><dfn id="vmax" lt="vmax">vmax unit</dfn>
<dd>
Equal to the larger of ''vw'' or ''vh''.
</dl>
<wpt>
css/css-values/vh-calc-support-pct.html
css/css-values/vh-calc-support.html
css/css-values/vh-em-inherit.html
css/css-values/vh-inherit.html
css/css-values/vh-interpolate-pct.html
css/css-values/vh-interpolate-px.html
css/css-values/vh-interpolate-vh.html
css/css-values/vh-support.html
css/css-values/vh-support-margin.html
css/css-values/vh-support-transform-origin.html
css/css-values/vh-support-transform-translate.html
css/css-values/vh-zero-support.html
css/css-values/vh_not_refreshing_on_chrome.html
css/css-values/viewport-relative-lengths-scaled-viewport.html
css/css-values/viewport-unit-011.html
css/css-values/viewport-units-css2-001.html
</wpt>
In situations where there is no root element
or it hasn't yet been styled
(such as when evaluating <a>media queries</a>),
the ''vi'' and ''vb'' units use the initial value of the 'writing-mode' property
to determine which axis they correspond to.
<!--
████████ ██ ██ ██ ████████ ████████ ██████
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
████████ ███ ██ ██████ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ████████ ██ ██████
-->
<h3 id="absolute-lengths">
Absolute Lengths: the ''cm'', ''mm'', ''Q'', ''in'', ''pt'', ''pc'', ''px'' units</h3>
The <dfn lt="absolute length">absolute length units</dfn> 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 <dfn export lt="physical unit">physical units</dfn> (''in'', ''cm'', ''mm'', ''pt'', ''pc'', ''Q'')
and the <dfn export lt="visual angle unit | pixel unit">visual angle unit (pixel unit)</dfn> (''px''):
<table class="data" export>
<thead>
<tr><th>unit
<th>name
<th>equivalence
<tbody dfn-type=value dfn-for="<length>">
<tr><th><dfn id="cm">cm</dfn>
<td>centimeters
<td>1cm = 96px/2.54
<tr><th><dfn id="mm">mm</dfn>
<td>millimeters
<td>1mm = 1/10th of 1cm
<tr><th><dfn id="Q">Q</dfn>
<td>quarter-millimeters
<td>1Q = 1/40th of 1cm
<tr><th><dfn id="in">in</dfn>
<td>inches
<td>1in = 2.54cm = 96px
<tr><th><dfn id="pc">pc</dfn>
<td>picas
<td>1pc = 1/6th of 1in
<tr><th><dfn id="pt">pt</dfn>
<td>points
<td>1pt = 1/72th of 1in
<tr><th><dfn id="px" lt="px">px</dfn>
<td>pixels
<td>1px = 1/96th of 1in
</table>
<div class="example">
<pre>
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 */
</pre>
</div>
All of the absolute length units are <a>compatible</a>,
and ''px'' is their <a>canonical unit</a>.
For a CSS device, these dimensions are <dfn lt="anchor unit | anchor">anchored</dfn> either
<ol type=i>
<li>by relating the <a>physical units</a> to their physical measurements, or
<li>by relating the <a>pixel unit</a> to the <a>reference pixel</a>.
</ol>
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 the earlier editions of CSS1 and CSS2.
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 unfortunate change
was made because too much existing content relies on the assumption of 96dpi,
and breaking that assumption broke the content.)
Note: Units are [=ASCII case-insensitive=] and serialize as lower case, for example 1Q serializes as 1q.
<wpt>
css/css-values/absolute-length-units-001.html
css/css-values/q-unit-case-insensitivity-001.html
css/css-values/q-unit-case-insensitivity-002.html
css/CSS2/values/units-001.xht
css/CSS2/values/units-006.xht
css/CSS2/values/units-008.xht
css/CSS2/values/units-009.xht
</wpt>
The <dfn export>reference pixel</dfn> 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&nbsp;mm (1/96&nbsp;inch).
The image below illustrates the effect of viewing distance on the size of a reference pixel:
a reading distance of 71&nbsp;cm (28&nbsp;inches)
results in a reference pixel of 0.26&nbsp;mm,
while a reading distance of 3.5&nbsp;m (12&nbsp;feet)
results in a reference pixel of 1.3&nbsp;mm.
<figure>
<img src="images/pixel1.png"
alt="This diagram illustrates how the definition of a pixel
depends on the users distance from the viewing surface
(paper or screen).
The image depicts the user looking at two planes, one
28 inches (71 cm) from the user, the second 140 inches
(3.5 m) from the user. An expanding cone is projected
from the user's eye onto each plane. Where the cone
strikes the first plane, the projected pixel is 0.26 mm
high. Where the cone strikes the second plane, the
projected pixel is 1.4 mm high.">
<figcaption>Showing that pixels must become larger if the viewing distance increases</figcaption>
</figure>
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).
<figure>
<img src="images/pixel2.png"
alt='This diagram illustrates the relationship between the
reference pixel and device pixels (called "dots" below).
The image depicts a high resolution (large dot density)
laser printer output on the left and a low resolution
monitor screen on the right. For the laser printer, one
square reference pixel is implemented by 16 dots. For
the monitor screen, one square reference pixel is
implemented by a single dot.'>
<figcaption>Showing that more device pixels (dots) are needed to cover a 1px by 1px area
on a high-resolution device than on a lower-resolution one
(of the same approximate viewing distance)</figcaption>
</figure>
<wpt>
css/css-values/absolute-length-units-001.html
</wpt>
<h2 id="other-units">
Other Quantities</h2>
<!--
███ ██ ██ ██████ ██ ████████
██ ██ ███ ██ ██ ██ ██ ██
██ ██ ████ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ████ ██ ██████
█████████ ██ ████ ██ ██ ██ ██
██ ██ ██ ███ ██ ██ ██ ██
██ ██ ██ ██ ██████ ████████ ████████
-->
<h3 id="angles">
Angle Units: the <<angle>> type and ''deg'', ''grad'', ''rad'', ''turn'' units</h3>
Angle values are <<dimension>>s denoted by <dfn id="angle-value">&lt;angle></dfn>.
The angle unit identifiers are:
<dl export dfn-type=value dfn-for="<angle>">
<dt><dfn id="deg">deg</dfn>
<dd>
Degrees. There are 360 degrees in a full circle.
<dt><dfn id="grad">grad</dfn>
<dd>
Gradians, also known as "gons" or "grades".
There are 400 gradians in a full circle.
<dt><dfn id="rad">rad</dfn>
<dd>
Radians. There are 2&pi; radians in a full circle.
<dt><dfn id="turn">turn</dfn>
<dd>
Turns. There is 1 turn in a full circle.
</dl>
For example, a right angle is ''90deg'' or ''100grad'' or ''0.25turn'' or
approximately ''1.57rad''.
All <<angle>> units are <a>compatible</a>,
and ''deg'' is their <a>canonical unit</a>.
<div class="note">
By convention,
when an angle denotes a direction in CSS,
it is typically interpreted as a <dfn export>bearing angle</dfn>,
where 0deg is "up" or "north" on the screen,
and larger angles are more clockwise
(so 90deg is "right" or "east").
For example, in the ''linear-gradient()'' function,
the <<angle>> that determines the direction of the gradient
is interpreted as a bearing angle.
</div>
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.
<wpt>
css/css-values/angle-units-001.html
css/css-values/angle-units-002.html
css/css-values/angle-units-003.html
css/css-values/angle-units-004.html
css/css-values/angle-units-005.html
css/css-values/calc-angle-values.html
</wpt>
<!--
████████ ████ ██ ██ ████████
██ ██ ███ ███ ██
██ ██ ████ ████ ██
██ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██
██ ██ ██ ██ ██
██ ████ ██ ██ ████████
-->
<h3 id="time">
Duration Units: the <<time>> type and ''s'', ''ms'' units</h3>
Time values are <a>dimensions</a> denoted by <dfn id="time-value">&lt;time></dfn>.
The time unit identifiers are:
<dl export dfn-type=value dfn-for="<time>">
<dt><dfn id="s">s</dfn>
<dd>Seconds.
<dt><dfn id="ms">ms</dfn>
<dd>Milliseconds. There are 1000 milliseconds in a second.
</dl>
All <<time>> units are <a>compatible</a>,
and ''s'' is their <a>canonical unit</a>.
Properties may restrict the time value to some range.
If the value is outside the allowed range,
the declaration is invalid and must be <a href="https://www.w3.org/TR/CSS21/conform.html#ignore">ignored</a>.
<wpt>
css/css-values/calc-time-values.html
css/css-transitions/transition-delay-001.html
css/css-transitions/transition-duration-001.html
</wpt>
<!--
████████ ████████ ████████ ███████ ██ ██ ████████ ██ ██ ██████ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ████
██████ ████████ ██████ ██ ██ ██ ██ ██████ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██ ██ ██
██ ██ ██ ████████ █████ ██ ███████ ████████ ██ ██ ██████ ██
-->
<h3 id="frequency">
Frequency Units: the <<frequency>> type and ''Hz'', ''kHz'' units</h3>
Frequency values are <a>dimensions</a> denoted by <dfn id="frequency-value">&lt;frequency></dfn>.
The frequency unit identifiers are:
<dl export dfn-type=value dfn-for="<frequency>">
<dt><dfn id="Hz">Hz</dfn>
<dd>Hertz. It represents the number of occurrences per second.
<dt><dfn id="kHz">kHz</dfn>
<dd>KiloHertz. A kiloHertz is 1000 Hertz.
</dl>
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 <a>compatible</a>,
and ''hz'' is their <a>canonical unit</a>.
Note: Units are [=ASCII case-insensitive=] and serialize as lower case, for example 1Hz serializes as 1hz.
<!--
████████ ████████ ██████ ███████
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██
████████ ██████ ██████ ██ ██
██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ████████ ██████ ███████
-->
<h3 id="resolution">
Resolution Units: the <<resolution>> type and ''&lt;resolution&gt;/dpi'', ''&lt;resolution&gt;/dpcm'', ''&lt;resolution&gt;/dppx'' units</h3>
Resolution units are <a>dimensions</a> denoted by <dfn id="resolution-value">&lt;resolution></dfn>.
The resolution unit identifiers are:
<dl export dfn-type=value dfn-for="<resolution>">
<dt><dfn id="dpi">dpi</dfn>
<dd>Dots per inch.
<dt><dfn id="dpcm">dpcm</dfn>
<dd>Dots per centimeter.
<dt><dfn id="dppx">dppx</dfn>
<dt><dfn id="x">x</dfn>
<dd>Dots per ''px'' unit.
</dl>
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 <a>compatible</a>,
and ''&lt;resolution>/dppx'' is their <a>canonical unit</a>.
<p class="note">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'.
<div class="example">
The following @media rule uses Media Queries [[MEDIAQ]]
to assign some special style rules to devices that use two or more device pixels per CSS ''px'' unit:
<pre>@media (min-resolution: 2dppx) { ... }</pre>
</div>
<h2 id="defined-elsewhere">
Data Types Defined Elsewhere</h2>
Some data types are defined in their own modules.
This example talks about some of the most common ones
used across several specifications.
<!--
██████ ███████ ██ ███████ ████████
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ████████
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██████ ███████ ████████ ███████ ██ ██
-->
<h3 id="colors">
Colors: the <<color>> type</h3>
The <<color>> data type is defined in [[!CSS3COLOR]].
UAs that support CSS Color Level 3 or its successor must interpret <<color>> as defined therein.
<h4 id="combine-colors">
Combination of <<color>></h4>
<a>Interpolation</a> 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).
<a>Addition</a> of <<color>> is likewise defined as
the independent <a>addition</a> of each component
as a <<number>>
in premultiplied space.
ISSUE: Computed value needs to be able to represent
combinations of ''currentColor'' and an actual color.
Consider the value of 'text-emphasis-color' in
<code>div { text-emphasis: circle; transition: all 2s; }<br>
div:hover { text-emphasis-color: lime; }<br>
em { color: red; }</code>
See <a href="https://github.com/w3c/csswg-drafts/issues/445">Issue 445</a>.
<!--
████ ██ ██ ███ ██████ ████████
██ ███ ███ ██ ██ ██ ██ ██
██ ████ ████ ██ ██ ██ ██
██ ██ ███ ██ ██ ██ ██ ████ ██████
██ ██ ██ █████████ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
████ ██ ██ ██ ██ ██████ ████████
-->
<h3 id="images">
Images: the <<image>> type</h3>
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>>.
<h4 id="combine-images">
Combination of <<image>></h4>
Note: Interpolation of <<image>> is defined in [[css-images-3#interpolation]].
Images are <a>not additive</a>.
<!--
████████ ███████ ██████ ████ ████████ ████ ███████ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
████████ ██ ██ ██████ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███
██ ███████ ██████ ████ ██ ████ ███████ ██ ██
-->
<h3 id="position">
2D Positioning: the <<position>> type</h3>
The <dfn><<position>></dfn> 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]]
<pre class=prod>
<<position>> = [
[ left | center | right ] || [ top | center | bottom ]
|
[ left | center | right | <<length-percentage>> ]
[ top | center | bottom | <<length-percentage>> ]?
|
[ [ left | right ] <<length-percentage>> ] &amp;&amp;
[ [ top | bottom ] <<length-percentage>> ]
]
</pre>
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 <em>greedily</em> parsed;
it consumes as many components as possible.
<div class=example>
For example,
'transform-origin' defines a 3D position
as (effectively) ''<<position>> <<length>>?''.
A value such as ''left 50px''
will be parsed as a 2-value <<position>>,
with an omitted z-component;
on the other hand,
a value such as ''top 50px''
will be parsed as a single-value <<position>>
followed by a <<length>>.
</div>
<h4 id="combine-positions">
Combination of <<position>></h4>
<a>Interpolation</a> 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>>.
<a>Addition</a> of <<position>> is likewise defined as
the independent <a>addition</a> each component (x, y)
normalized as an offset from the top left corner
as a <<length-percentage>>.
<!--
████████ ██ ██ ██ ██ ██████ ██████
██ ██ ██ ███ ██ ██ ██ ██ ██
██ ██ ██ ████ ██ ██ ██
██████ ██ ██ ██ ██ ██ ██ ██████
██ ██ ██ ██ ████ ██ ██
██ ██ ██ ██ ███ ██ ██ ██ ██
██ ███████ ██ ██ ██████ ██████
-->
<h2 id="functional-notations">
Functional Notations</h2>
A <dfn export>functional notation</dfn> 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.
<a href="https://www.w3.org/TR/css-syntax/#whitespace">White space</a> is allowed, but optional,
immediately inside the parentheses.
Functions can take multiple arguments,
which are formatted similarly to a CSS property value.
Some legacy <a>functional notations</a>, 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,
<a href="https://www.w3.org/TR/css-syntax/#whitespace">white space</a> is optional before and after the comma.
<div class="example">
<pre>
background: url(http://www.example.org/image);
color: rgb(100, 200, 50 );
content: counter(list-item) ". ";
width: calc(50% - 2em);
</pre>
</div>
The [=math functions=] are defined in [[#math]].
<!--
████████ ███████ ██████ ██████ ██ ████████ ███ ███
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ████ ██ ████ ██ ██████ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ███████ ██████ ██████ ████████ ████████ ███ ███
-->
<h3 id="toggle-notation">
Toggling Between Values: ''toggle()''</h3>
The <dfn>toggle()</dfn> expression allows descendant elements
to cycle over a list of values instead of inheriting the same value.
<div class='example'>
The following example makes <code>&lt;em></code> elements italic in general,
but makes them normal if they're inside something that's italic:
<pre>em { font-style: toggle(italic, normal); }</pre>
</div>
<div class='example'>
The following example cycles markers for nested lists,
so that a top level list has ''list-style-type/disc''-shaped markers,
but nested lists use ''list-style-type/circle'', then ''list-style-type/square'', then ''list-style-type/box'',
and then repeat through the list of marker shapes,
starting again (for the 5th list deep) with ''list-style-type/disc''.
<pre>ul { list-style-type: toggle(disc, circle, square, box); }</pre>
</div>
The syntax of the ''toggle()'' expression is:
<pre>toggle( <<toggle-value>># )</pre>
where <dfn>&lt;toggle-value></dfn> 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.
<div class="example">
The following ''toggle()'' examples are all invalid:
<pre>
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' */
</pre>
</div>
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 <var>C<sub>n</sub></var> for the <var>n</var>-th argument to ''toggle()''.
Then, compare the property's <a>inherited value</a>
with each <var>C<sub>n</sub></var>.
For the earliest <var>C<sub>n</sub></var> that matches the <a>inherited value</a>,
the computed value of ''toggle()'' is <var>C<sub>n+1</sub></var>.
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)''.
<!-- Issue: Should this short-circuiting affect the computed value? -->
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 <a href="https://www.w3.org/TR/CSS21/cascade.html#computed-value">computed value</a> 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 <l spec=css2>'background-position'</l> 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 <a href="#status">provide feedback</a> so we can fix it.
If ''toggle()'' is used on a <a>shorthand property</a>,
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 <a>shorthand</a>.
<div class="example">
For example, the following shorthand declaration:
<pre>margin: toggle(1px 2px, 4px, 1px 5px 4px);</pre>
is equivalent to the following longhand declarations:
<pre>
margin-top: toggle(1px, 4px, 1px);
margin-right: toggle(2px, 4px, 5px);
margin-bottom: toggle(1px, 4px, 4px);
margin-left: toggle(2px, 4px, 5px);
</pre>
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:
<pre>
margin-top: toggle(1px, 4px);
margin-right: toggle(2px, 4px, 5px);
margin-bottom: toggle(1px, 4px);
margin-left: toggle(2px, 4px, 5px);
</pre>
which may not be what was intended.
</div>
<!--
███ ████████ ████████ ████████ ███ ███
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ████████ ██ ██
█████████ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ███ ███
-->
<h2 id="attr-notation">
Attribute References: the ''attr()'' function</h2>
<!--
Ian's proposal:
http://lists.w3.org/Archives/Member/w3c-css-wg/2002OctDec/0141.html
-->
The <dfn>attr()</dfn> function substitutes the value of an <l spec=dom>[=attribute=]</l> on an <l spec=dom>[=/element=]</l>
into a property,
similar to how the ''var()'' function
substitutes a [=custom property=] value into a function.
<pre class=prod>
attr() = attr( <<wq-name>> <<attr-type>>? , <<declaration-value>>?)
<dfn>&lt;attr-type></dfn> = string | url | ident | color | number | percentage |
length | angle | time | frequency | flex | <<dimension-unit>>
</pre>
The <dfn>&lt;dimension-unit></dfn> 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:
: <<wq-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 <<wq-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 <dfn dfn for=attr()>substitution value</dfn>)
and what, if any, special parsing will be done to the value.
The possible values and their behavior are defined in [[#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 [=substitute an attr()|substituted=].
<div class='note'>
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 <css>auto</css>,
like in ''width: attr(size px, auto);''.
</div>
<h3 id="attr-types">
''attr()'' Types</h3>
The behavior of the ''attr()'' function
depends partially on the value of the <<attr-type>> argument:
<dl dfn-type=value dfn-for=attr()>
: <dfn>string</dfn>
:: 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.
: <dfn>url</dfn>
:: 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.
: <dfn>ident</dfn>
:: The [=substitution value=] is a CSS <<custom-ident>>,
whose value is the literal value of the attribute,
with [=strip leading and trailing ASCII whitespace|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 <css>default</css>,
there is instead no [=substitution value=].
: <dfn>color</dfn>
::
[=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=].
: <dfn>number</dfn>
::
[=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=].
: <dfn>percentage</dfn>
::
[=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=].
: <dfn>length</dfn>
: <dfn>angle</dfn>
: <dfn>time</dfn>
: <dfn>frequency</dfn>
: <dfn>flex</dfn>
::
[=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=].
: <dfn><<dimension-unit>></dfn>
::
[=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=].
</dl>
Issue: 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;
<code highlight=html>foo="rgb(var(--red), 0, 0)"</code>
needs to be illegal for ''attr(foo color)''.
<div class="example">
This example shows the use of attr() to visually illustrate data
in an XML file:
<pre>
&lt;stock>
&lt;wood length="12"/>
&lt;wood length="5"/>
&lt;metal length="19"/>
&lt;wood length="4"/>
&lt;/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);
}
</pre>
</div>
<h3 id=attr-substitution>
''attr()'' Substitution</h3>
Issue: 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 [=substitute an attr()|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 <dfn export>substitute an ''attr()''</dfn>:
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 an attr()|substitute=] them as well.
3. Otherwise, the property containing the ''attr()'' function
is [=invalid at computed-value time=].
<!--
██████ ███ ██ ██████ ███ ███
██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██
██ █████████ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██
██████ ██ ██ ████████ ██████ ███ ███
-->
<h2 id="math" oldids="calc-notation">
Mathematical Expressions</h2>
The <dfn export lt="math function">math functions</dfn>
(''calc()'', ''clamp()'', ''sin()'',
and others defined in this chapter)
allow numeric CSS values
to be written as mathematical expressions.
A [=math function=] represents a numeric value,
one of:
* <<length>>,
* <<frequency>>,
* <<angle>>,
* <<time>>,
* <<flex>>,
* <<resolution>>,
* <<percentage>>,
* <<number>>,
* <<integer>>
...or the <<length-percentage>>/etc mixed types,
and can be used wherever such a value would be valid.
<h3 id=calc-func>
Basic Arithmetic: ''calc()''</h3>
The <dfn>calc()</dfn> function is a [=math function=]
that allows basic arithmetic to be performed on numerical values,
using addition (<css>+</css>), subtraction (<css>-</css>), multiplication (<css>*</css>), division (<css>/</css>),
and parentheses.
A ''calc()'' function contains a single <dfn export for="calc()">calculation</dfn>,
which is a sequence of values interspersed with operators,
and possibly grouped by parentheses
(matching the <<calc-sum>> grammar),
which represents the result of evaluating the expression
using standard operator precedence rules
(<css>*</css> and <css>/</css> bind tighter than <css>+</css> and <css>-</css>,
and operators are otherwise evaluated left-to-right).
The ''calc()'' function represents the result of its contained [=calculation=].
Components of a [=calculation=] can be literal values
(such as ''5px''),
other [=math functions=],
or other expressions, such as ''attr()'',
that evaluate to a valid argument type (like <<length>>).
<div class="example">
[=Math functions=] can be used to combine value that use different units.
In this example the author wants the <em>margin box</em> of each section
to take up 1/3 of the space,
so they start with <css>100%/3</css>,
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.)
<pre class=lang-css>
section {
float: left;
margin: 1em; border: solid 1px;
width: calc(100% / 3 - 2 * 1em - 2 * 1px);
}
</pre>
Similarly, in this example the gradient will show a color transition
only in the first and last ''20px'' of the element:
<pre class=lang-css>
.fade {
background-image: linear-gradient(silver 0%, white 20px,
white calc(100% - 20px), silver 100%);
}
</pre>
</div>
<div class="example">
[=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.
<pre class=lang-css>
:root {
font-size: calc(100vw / 35);
}
</pre>
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.
</div>
<div class="example">
Standard mathematical precedence rules for the operators apply:
''calc(2 + 3 * 4)'' is equal to ''14'',
not ''20''.
Parentheses can be used to manipulate precedence:
''calc((2 + 3) * 4)'' is instead equal to ''20''.
Parentheses and nesting additional ''calc()'' functions are equivalent;
the preceding expression could equivalently have been written as
''calc(calc(2 + 3) * 4)''.
This can be useful when building up values piecemeal via ''var()'',
such as in the following example:
<pre class=lang-css>
.aspect-ratio-box {
--ar: calc(16 / 9);
--w: calc(100% / 3);
--h: calc(var(--w) / var(--ar));
width: var(--w);
height: var(--h);
}
</pre>
Altho '--ar' <em>could</em> have been written as simply
''--ar: (16 / 9);'',
'--w' is used both on its own (in 'width')
and as a ''calc()'' component (in '--h'),
so it has to be written as a full ''calc()'' function itself.
</div>
<wpt>
css/css-values/calc-ch-ex-lang.html
css/css-values/calc-in-color-001.html
css/css-values/calc-in-font-feature-settings.html
css/css-values/calc-rem-lang.html
css/css-values/calc-rounding-001.html
css/css-values/ex-calc-expression-001.html
</wpt>
<h3 id=comp-func>
Comparison Functions: ''min()'', ''max()'', and ''clamp()''</h3>
The comparison functions of ''min()'', ''max()'', and ''clamp()''
compare multiple [=calculations=]
and represent the value of one of them.
The <dfn>min()</dfn> or <dfn>max()</dfn> functions
contain one or more comma-separated [=calculations=],
and represent the smallest (most negative) or largest (most positive) of them, respectively.
The <dfn>clamp()</dfn> function takes three [=calculations=]--
a minimum value, a central value, and a maximum value--
and represents its central calculation,
clamped according to its min and max calculations,
favoring the min calculation if it conflicts with the max.
(That is, given ''clamp(MIN, VAL, MAX)'',
it represents exactly the same value as ''max(MIN, min(VAL, MAX))'').
<div class="example">
''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:
<pre class=lang-css>
.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);
}
</pre>
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.
</div>
<div class="example">
An occasional point of confusion when using ''min()''/''max()''
is that you use ''max()'' to impose a minimum value on something
(that is, properties like 'min-width' effectively use ''max()''),
and ''min()'' to impose a maximum value on something;
it's easy to accidentally reach for the opposite function
and try to use ''min()'' to add a minimum size.
Using ''clamp()'' can make the code read more naturally,
as the value is nestled between its minimum and maximum:
<pre class=lang-css>
.type {
/* Force the font-size to stay between 12px and 100px */
font-size: clamp(12px, 10 * (1vw + 1vh) / 2, 100px);
}
</pre>
</div>
<div class=note>
Note that ''clamp()'',
matching CSS conventions elsewhere,
has its minimum value "win" over its maximum value
if the two are in the "wrong order".
That is, ''clamp(100px, ..., 50px)''
will resolve to ''100px'',
exceeding its stated "max" value.
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.
</div>
<h3 id=round-func>
Stepped Value Functions: ''round()'', ''mod()'', and ''rem()''</h3>
The stepped-value functions,
''round()'', ''mod()'', and ''rem()'',
all transform a given value
according to another "step value",
in different ways.
The <dfn lt="round()">round(<<rounding-strategy>>?, A, B)</dfn> function
contains an optional rounding strategy,
and two [=calculations=] A and B,
and returns the value of A,
rounded according to the rounding strategy,
to the nearest integer multiple of B either above or below A.
The argument [=calculations=] can resolve to any <<number>>, <<dimension>>, or <<percentage>>,
but must have the <em>same</em> [=determine the type of a calculation|type=],
or else the function is invalid;
the result will have the same [=CSSNumericValue/type=] as the arguments.
If A is exactly equal to an integer multiple of B,
''round()'' resolves to A exactly
(preserving whether A is 0⁻ or 0⁺, if relevant).
Otherwise, there are two integer multiples of B that are potentially "closest" to A,
|lower B| which is closer to −∞
and |upper B| which is closer to +∞.
The following <dfn><<rounding-strategy>></dfn>s dictate how to choose between them:
<dl dfn-type=value dfn-for="<rounding-strategy>">
: <dfn>nearest</dfn>
:: Choose whichever of |lower B| and |upper B|
that has the smallest absolute difference from A.
If both have an equal difference
(A is exactly between the two values),
choose |upper B|.
: <dfn>up</dfn>
:: Choose |upper B|.
: <dfn>down</dfn>
:: Choose |lower B|.
: <dfn>to-zero</dfn>
:: Choose whichever of |lower B| and |upper B|
that has the smallest absolute difference from 0.
</dl>
If |lower B| would be zero,
it is specifically equal to 0⁺;
if |upper B| would be zero,
it is specifically equal to 0⁻.
If <<rounding-strategy>> is omitted,
it defaults to ''nearest''.
Issue(5689): CSSOM needs to specify how it rounds,
and it's probably good for CSS functions to round the same way by default.
What behavior should be used?
<div class=example>
Unlike languages like JavaScript
which have a natural "precision" to round to
(integers),
CSS values have no such precision
because values can be written in many different compatible units.
As such, the precision has to be given explicitly;
to round a width to the nearest ''50px'',
one can write ''round(var(--width), 50px)''.
</div>
Note: JavaScript and other programming languages
sometimes separate out the rounding strategies into separate rounding functions.
JS’s <code highlight=JS>Math.floor()</code>
is equivalent to CSS's ''round(down, ...)'';
JS’s <code highlight=JS>Math.ceil()</code>
is equivalent to CSS's ''round(up, ...)'';
JS’s <code highlight=JS>Math.trunc()</code>
is equivalent to CSS's ''round(to-zero, ...)'';
and JS’s <code highlight=JS>Math.round()</code>
is equivalent to CSS's ''round(nearest, ...)'',
or just ''round(...)''.
Note: The <<rounding-strategy>> keywords
are the same as the keywords in 'block-step-size'
and have the same behavior.
('block-step-size' just lacks ''to-zero'';
since block sizes are always non-negative,
''to-zero'' and ''down'' would be identical.)
The modulus functions <dfn lt="mod()">mod(A, B)</dfn>
and <dfn lt=rem()>rem(A, B)</dfn>
similarly contain two [=calculations=] A and B,
and return the difference between A
and the nearest integer multiple of B either above or below A.
The argument [=calculations=] can resolve to any <<number>>, <<dimension>>, or <<percentage>>,
but must have the <em>same</em> [=determine the type of a calculation|type=],
or else the function is invalid;
the result will have the same [=CSSNumericValue/type=] as the arguments.
The two functions are very similar,
and in fact return identical results
if both arguments are positive or both are negative:
the value of the function is equal to the value of A
shifted by the integer multiple of B
that brings the value <dfn noexport>between zero and B</dfn>.
(Specifically, the range includes zero
and excludes B.
More specifically, if B is positive the range starts at 0⁺,
and if B is negative it starts at 0⁻.)
<div class=example>
For example, ''mod(18px, 5px)'' resolves to the value ''3px'',
because subtracting ''5px * 3'' from ''18px'' yields ''3px'',
which is the only such value between ''0px'' and ''3px''.
Similarly, ''mod(-140deg, -90deg)'' resolves to the value ''-50deg'',
because adding ''-90deg * 1'' to ''-140deg'' yields ''-50deg'',
which is the only such value between ''0deg'' and ''-90deg''.
Evaluating either of these examples with ''rem()'' yields the exact same results.
</div>
Their behavior diverges if the A value and the B step
are on opposite sides of zero:
''mod()'' (short for “modulus”)
continues to choose the integer multiple of B
that puts the value [=between zero and B=], as above
(guaranteeing that the result will either be zero
or share the sign of B, not A),
while ''rem()'' (short for "remainder")
chooses the integer multiple of B
that puts the value [=between zero and B|between zero and -B=],
avoiding changing the sign of the value.
<div class=example>
For example, ''mod(-18px, 5px)'' resolves to the value ''2px'':
adding ''5px * 4'' to ''-18px'' yields ''2px'',
which is between ''0px'' and ''5px''.
On the other hand, ''rem(-18px, 5px)'' resolves to the value ''-3px'':
adding ''5px * 3'' to ''-18px'' yields ''-3px'',
which has the same sign as ''-18px''
but is between ''0px'' and ''-5px''.
Similarly, ''mod(140deg, -90deg)'' resolves to the value ''-40deg''
(adding ''-90deg * 2'' to ''140deg'',
bringing it to between ''0deg'' and ''-90deg''),
but ''rem(140deg, -90deg)'' resolves to the value ''50deg''.
</div>
<details>
<summary>When should I choose ''mod()'' vs ''rem()''?</summary>
Typically, users of this operation
are in control of the step value (B),
and are modifying an unknown value A.
As a result, it's <em>usually</em> more expected
that the result is between 0 and B,
regardless of A's sign,
meaning ''mod()'' should be chosen.
For example,
if an author wants to know whether a length
is an even or odd number of pixels,
''mod(A, 2px)'' will return either ''0px'' or ''1px''
(assuming the value is a whole number of pixels to begin with),
regardless of the value of a.
''rem(A, 2px)'', on the other hand,
will return ''0px'' if A is an even number of pixels,
but will return <em>either</em> ''1px'' or ''-1px''
if it's odd,
depending on whether A is positive or negative.
The opposite situation does sometimes occur,
however,
and so ''rem()'' is provided to cater to that.
As well, ''rem()'' is the behavior of JavaScript's <code highlight=js>%</code> operator,
so if an exact match between CSS and JS code is desired,
''rem()'' can be useful.
</details>
Note: ''mod()'' and ''rem()''
can also be defined directly in terms of other functions:
''mod(A, B)'' is equivalent to ''calc(A - sign(B)*round(down, A*sign(B), B))''
(a hacky way to say "round(down) when B is positive, round(up) when B is negative),
while ''rem(A, B)'' is equivalent to ''calc(A - round(to-zero, A, B))''.
(These expressions don't always handle 0⁺ and 0⁻ correctly, though,
because 0⁻ semantics aren't commutative for addition.)
<h4 id=round-infinities>
Argument Ranges</h4>
In ''round(A, B)'',
if B is 0,
the result is NaN.
If A and B are both infinite,
the result is NaN.
If A is infinite but B is finite,
the result is the same infinity.
If A is finite but B is infinite,
the result depends on the <<rounding-strategy>>
and the sign of A:
: ''nearest''
: ''to-zero''
:: If A is positive or 0⁺, return 0⁺.
Otherwise, return 0⁻.
: ''up''
:: If A is positive (not zero), return +∞.
If A is 0⁺, return 0⁺.
Otherwise, return 0⁻.
: ''down''
:: If A is negative (not zero), return −∞.
If A is 0⁻, return 0⁻.
Otherwise, return 0⁺.
In ''mod(A, B)'' or ''rem(A, B)'',
if B is 0,
the result is NaN.
If A is infinite,
the result is NaN.
In ''mod(A, B)'' only,
if B is infinite
and A is non-zero and has opposite sign to B,
the result is NaN.
Note: All other "infinite B" cases are valid,
and just return A immediately.
<h3 id=trig-funcs>
Trigonometric Functions: ''sin()'', ''cos()'', ''tan()'', ''asin()'', ''acos()'', ''atan()'', and ''atan2()''</h3>
The trigonometric functions--
''sin()'', ''cos()'', ''tan()'', ''asin()'', ''acos()'', ''atan()'', and ''atan2()''--
compute the various basic trigonometric relationships.
The <dfn lt="sin()">sin(A)</dfn>, <dfn lt="cos()">cos(A)</dfn>, and <dfn lt="tan()">tan(A)</dfn> functions
all contain a single [=calculation=]
which must resolve to either a <<number>>
or an <<angle>>,
and compute their corresponding function
by interpreting the result of their argument as radians.
(That is, ''sin(45deg)'', ''sin(.125turn)'', and ''sin(3.14159 / 4)''
all represent the same value,
approximately ''.707''.)
They all represent a <<number>>;
''sin()'' and ''cos()'' will always return a number between −1 and 1,
while ''tan()'' can return any number between −∞ and +∞.
(See [[#calc-type-checking]] for details on how [=math functions=] handle ∞.)
The <dfn lt="asin()">asin(A)</dfn>, <dfn lt="acos()">acos(A)</dfn>, and <dfn lt="atan()">atan(A)</dfn> functions
are the "arc" or "inverse" trigonometric functions,
representing the inverse function to their corresponding "normal" trig functions.
All of them contain a single [=calculation=]
which must resolve to a <<number>>,
and compute their corresponding function,
interpreting their result as a number of radians,
representing an <<angle>>.
The angle returned by ''asin()'' must be normalized to the range [''-90deg'', ''90deg''];
the angle returned by ''acos()'' to the range [''0deg'', ''180deg''];
and the angle returned by ''atan()'' to the range [''-90deg'', ''90deg''].
The <dfn lt="atan2()">atan2(A, B)</dfn> function
contains two comma-separated [=calculations=], A and B.
A and B can resolve to any <<number>>, <<dimension>>, or <<percentage>>,
but must have the <em>same</em> [=determine the type of a calculation|type=],
or else the function is invalid.
The function returns the <<angle>>
between the positive X-axis and the point (B,A).
The returned angle must be normalized to the interval (''-180deg'', ''180deg'']
(that is, greater than ''-180deg'', and less than or equal to ''180deg'').
Note: ''atan2(Y, X)'' is <em>generally</em> equivalent to ''atan(Y / X)'',
but it gives a better answer when the point in question may include negative components.
''atan2(1, -1)'', corresponding to the point (-1, 1),
returns ''135deg'',
distinct from ''atan2(-1, 1)'', corresponding to the point (1, -1),
which returns ''-45deg''.
In contrast, ''atan(1 / -1)'' and ''atan(-1 / 1)'' both return''-45deg'',
because the internal calculation resolves to ''-1'' for both.
<h4 id="trig-infinities">
Argument Ranges</h4>
In ''sin(A)'', ''cos(A)'', or ''tan(A)'',
if A is infinite,
the result is NaN.
(See [[#calc-type-checking]] for details on how [=math functions=] handle NaN.)
In ''sin(A)'' or ''tan(A)'',
if A is 0⁻,
the result is 0⁻.
In ''tan(A)'', if A is one of the asymptote values
(such as ''90deg'', ''270deg'', etc),
the result must be +∞ for ''90deg'' and all values a multiple of ''360deg'' from that
(such as ''-270deg'' or ''450deg''),
and −∞ for ''-90deg'' and all values a multiple of ''360deg'' from that
(such as ''-450deg'' or ''270deg'').
Note: This is only relevant for units that can exactly represent the asymptotic values,
such as ''deg'' or ''grad''.
''rad'' cannot,
and so whether the result is a very large negative or positive value
can depend on rounding and precise details of how numbers are internally stored.
It's recommended you don't depend on this behavior if using such units.
In ''asin(A)'' or ''acos(A)'',
if A is less than -1 or greater than 1,
the result is NaN.
In ''acos(A)'',
if A is exactly 1,
the result is 0.
In ''asin(A)'' or ''atan(A)'',
if A is 0⁻,
the result is 0⁻.
In ''atan(A)'',
if A is +∞,
the result is ''90deg'';
if A is −∞,
the result is ''-90deg''.
In ''atan2(Y, X)'',
the following table gives the results for all unusual argument combinations:
<table class=data>
<thead>
<tr><td style="border:none" colspan=2><th colspan=6>X
<tr><td style="border:none" colspan=2><th>−∞ <th>-finite <th>0⁻ <th>0⁺ <th>+finite <th>+∞
</thead>
<tr>
<th rowspan=6 style="border-right:1px solid silver">Y
<th style="border-right: black 2px solid">−∞
<td>-135deg
<td>-90deg
<td>-90deg
<td>-90deg
<td>-90deg
<td>-45deg
<tr>
<th>-finite
<td>-180deg
<td>(normal)
<td>-90deg
<td>-90deg
<td>(normal)
<td>0⁻deg
<tr>
<th>0⁻
<td>-180deg
<td>-180deg
<td>-180deg
<td>0⁻deg
<td>0⁻deg
<td>0⁻deg
<tr>
<th>0⁺
<td>180deg
<td>180deg
<td>180deg
<td>0⁺deg
<td>0⁺deg
<td>0⁺deg
<tr>
<th>+finite
<td>180deg
<td>(normal)
<td>90deg
<td>90deg
<td>(normal)
<td>0⁺deg
<tr>
<th>+∞
<td>135deg
<td>90deg
<td>90deg
<td>90deg
<td>90deg
<td>45deg
</table>
Note: All of these behaviors are intended to match the "standard" definitions of these functions
as implemented by most programming languages,
in particular as implemented in JS.
Note: The behavior of ''tan(90deg)'',
while not constrained by JS behavior
(because the JS function's input is in radians,
and one cannot perfectly express a value of π/2 in JS numbers),
is defined so that roundtripping of values works;
''tan(atan(infinity))'' yields +∞,
''tan(atan(-infinity))'' yields −∞,
''atan(tan(90deg))'' yields ''90deg'',
and ''atan(tan(-90deg))'' yields ''-90deg''.
<h3 id=exponent-funcs>
Exponential Functions: ''pow()'', ''sqrt()'', ''hypot()'', ''log()'', ''exp()''</h3>
The exponential functions--
''pow()'', ''sqrt()'', ''hypot()'', ''log()'', and ''exp()''--
compute various exponential functions with their arguments.
The <dfn lt="