Copyright © 2011 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.
This CSS3 module describes the various values and units that CSS properties accept. Also, it describes how values are computed from "specified" through "computed" and "used" into "actual" values. The main purpose of this module is to define common values and units in one specification which can be referred to by other modules. As such, it does not make sense to claim conformance with this module alone.
This is a public copy of the editors' draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don't cite this document other than as work in progress.
The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-values” in the subject, preferably like this: “[css3-values] …summary of comment…”
This document was produced by the CSS Working Group (part of the Style Activity).
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
All features described in this specification that also exist in CSS 2.1 [CSS21] are intended to be backwards compatible. In case of conflict between this draft and CSS 2.1 [CSS21], CSS 2.1 probably represents the intention of the CSS WG better than this draft (other than on values and units that are new to CSS3).
The following features are at-risk and may be dropped during the CR
period: ‘vh
’,
‘vw
’, ‘vm
’, ‘fr
’, ‘gr
’, ‘cycle()
’, ‘attr()
’.
<length>
’ type
The value definition field of each CSS property can contain keywords,
data types (which appear between ‘<
’
and ‘>
’), and information on how they
can be combined. Generic data types (<length>
being the most widely
used) that can be used by many properties are described in this
specification, while more specific data types (e.g.,
<spacing-limit>
) are described in the corresponding
modules.
This module replaces and extends the data type definitions in [CSS21] sections 1.4.2.1, 4.3, and A.2.
The syntax described here is used to define the set of valid values for CSS properties. A property value can have one or more components.
Component value types are designated in several ways:
auto
’, ‘disc
’,
etc.), which appear literally, without quotes (e.g. auto
)
<
’ and ‘>
’ (e.g., <length>
, <percentage>
, etc.).
<'border-width'>
<'background-attachment'>
, etc.). In this case, the
type name is the property name (complete with quotes) between the
brackets. Such a type does not include the value ‘inherit
’.
<
’ and ‘>
’, as in <spacing-limit>
.
Notice the distinction between <border-width>
and
<'border-width'>
: the latter is defined as the value
of the ‘border-width
’ property,
the former requires an explicit expansion elsewhere. The definition of a
non-terminal is located near its first appearance in the specification.
Some property value definitions also include the slash (/) and/or the comma (,) as literals. These represent their corresponding tokens.
All CSS properties also accept the keyword values ‘inherit
’ and ‘initial
’ as their property value, but for
readability these are not listed explicitly in the property value syntax
definitions. These keywords cannot be combined with other component values
in same declaration; such a declaration is invalid. For example,
‘background: url(corner.png) no-repeat,
inherit;
’ is invalid.
Component values can be arranged into property values as follows:
Juxtaposition is stronger than the double ampersand, the double ampersand is stronger than the double bar, and the double bar is stronger than the bar. Thus, the following lines are equivalent:
a b | c || d && e f [ a b ] | [ c || [ d && [ e f ]]]
Every type, keyword, or bracketed group may be followed by one of the following modifiers:
Component values are specified in terms of tokens, as described in Chapter 4
of [CSS21]. As the
grammar allows spaces between tokens in the components of the
value
production, spaces may appear between tokens in
property values.
Note: In many cases, spaces will in fact be required
between tokens in order to distinguish them from each other. For example,
the value ‘1em2em
’ would be parsed as a
single DIMEN
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
’.
Below are some examples of properties with their corresponding value definition fields
Property | Value definition field | Example value |
---|---|---|
‘orphans ’
| <integer> | ‘3 ’
|
‘text-align ’
| left | right | center | justify | ‘center ’
|
‘padding-top ’
| <length> | <percentage> | ‘5% ’
|
‘outline-color ’
| <color> | invert | ‘#fefefe ’
|
‘text-decoration ’
| none | underline || overline || line-through || blink | ‘overline underline ’
|
‘font-family ’
| <family-name># | ‘"Gill Sans", Futura,
sans-serif ’
|
‘border-width ’
| [ <length> | thick | medium | thin ]{1,4} | ‘2px medium 4px ’
|
‘text-shadow ’
| [ inset? && [ <length>{2,4} && <color>? ] ]# | none | ‘3px 3px rgba(50%, 50%, 50%, 50%),
lemonchiffon 0 0 4px inset ’
|
‘voice-pitch ’
|
<frequency> && absolute | [[x-low | low | medium | high | x-high] || [<frequency> | <semitones> | <percentage>]] | ‘-2st x-low ’
|
An identifier is a sequence of characters
conforming to the IDENT
token in the grammar.
[CSS21] Identifiers
cannot be quoted; otherwise they would be interpreted as a string.
In the value definition fields, keywords with a pre-defined meaning appear literally. Keywords are CSS identifiers and are interpreted case-insensitively within the ASCII range (i.e., [a-z] and [A-Z] are equivalent).
For example, here is the value definition for the ‘border-collapse
’ property:
Value: collapse | separate
And here is an example of its use:
table { border-collapse: separate }
initial
’ and ‘inherit
’As defined above, all properties accept
the ‘initial
’ and ‘inherit
’ keywords, which represent value
computations common to all CSS properties.
The ‘inherit
’
keyword is defined
in [CSS21].
The ‘initial
’
keyword represents the specified value that is designated as the
property's initial value. [CSS3CASCADE]
It's been requested to have a value that rolls back to the
bottom of that level of the cascade, e.g. for an author rule it would roll
back to the end of the user cascade, for a user rule it would roll back to
the end of the UA cascade, and for the UA it would roll back to
‘initial
’/‘inherit
’. Is that something we should add, perhaps
using the reserved ‘default
’ keyword?
<identifier>
’ typeSome properties accept arbitrary user-defined identifiers as a component
value. This generic data type is denoted by <identifier>
, and represents
any valid CSS identifier that does not
otherwise appear as a pre-defined keyword in that property's value
definition. Such identifiers are fully case-sensitive, even in the ASCII
range (e.g. ‘example
’ and ‘EXAMPLE
’ are two different, unrelated user-defined
identifiers).
<string>
’ typeStrings are denoted by <string>
and consist of a
sequence of characters delimited by double quotes or single quotes. They
correspond to the STRING
token in the grammar.
[CSS21]
Double quotes cannot occur inside double quotes, unless escaped (as
‘\"
’ or as ‘\22
’). Analogously for single quotes
("\‘" or "\27").
content: "this is a 'string'."; content: "this is a \"string\"."; content: 'this is a "string".'; content: 'this is a \'string\'.';
It is possible to break strings over several lines, for aesthetic or other reasons, but in such a case the newline itself has to be escaped with a backslash (\). The newline is subsequently removed from the string. For instance, the following two selectors are exactly the same:
a[title="a not s\ o very long title"] {/*...*/} a[title="a not so very long title"] {/*...*/}
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.)
<url>
’‘ type
A URL is a pointer to a resource and is a specially-parsed functional notation denoted by <url>
. It corresponds to the
URI
token in the grammar.
[CSS21]
Below is an example of a URL being used as a background image:
body { background: url("http://www.example.com/pinkish.gif") }
The same example can be written without quotes:
body { background: url(http://www.example.com/pinkish.gif) }
Note that in some CSS syntactic contexts (as defined by that
context), a URL can be represented as a <string>
rather than by <URL>
. An example of this is the
’‘@import
’‘ rule
.
Parentheses, whitespace characters, single quotes (’) and double
quotes (") appearing in a URL must be escaped with a backslash so that the
resulting value is a valid URL
token, e.g.
‘url(open\(parens)
’, ‘url(close\)parens)
’. Depending on the type of URL,
it might also be possible to write these characters as URI-escapes (where
(
= %28
, )
= %29
,
etc.) as described in [URI]. Alternatively a URL containing
such characters may be represented as a quoted string within the ‘url()
’ notation.
In order to create modular style sheets that are not dependent on the absolute location of a resource, authors should use relative URIs. Relative URIs (as defined in [URI]) are resolved to full URIs using a base URI. RFC 3986, section 3, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.
For example, suppose the following rule:
body { background: url("tile.png") }
is located in a style sheet designated by the URL:
http://www.example.org/style/basic.css
The background of the source document's <body>
will
be tiled with whatever image is described by the resource designated by
the URL:
http://www.example.org/style/tile.png
The same image will be used regardless of the URL of the source
document containing the <body>
.
<integer>
’
typeInteger values are denoted by <integer>
. An integer is one or more decimal digits ‘0
’ through ‘9
’
and corresponds to a subset of the NUMBER
token in the grammar.
Integers may be immediately preceded by ‘-
’ or ‘+
’ to
indicate the sign.
Properties may restrict the integer value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
<number>
’ typeNumber values are denoted by <number>
. A number is either an integer,
or zero or more decimal digits followed by a dot (.) followed by one or
more decimal digits. It corresponds to the NUMBER
token in the grammar.
Like integers, numbers may also be immediately preceded by ‘-
’ or ‘+
’ to
indicate the sign.
Properties may restrict the number value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
<percentage>
’ typeA percentage value is denoted by <percentage>
, consists of a
<number> immediately followed by
a percent sign ‘%
’. It corresponds to
the PERCENTAGE
token in the grammar.
Percentage values are always relative to another value, for example a length. Each property that allows percentages also defines the value to which the percentage refers. The value may be that of another property for the same element, a property for an ancestor element, or a value of the formatting context (e.g., the width of a containing block). When a percentage value is set for a property of the root element and the percentage is defined as referring to the inherited value of some property, the resultant value is the percentage times the initial value of that property.
Properties may restrict the percentage value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
<length>
’ typeLengths refer to distance measurements and are denoted by <length>
in the property
definitions. A length is a dimension. A
zero length may be represented instead as the <number>
‘0
’. (In other words, for zero lengths the unit
identifier is optional.)
A dimension is a number immediately followed by a unit
identifier. It corresponds to the DIMENSION
token in the grammar.
[CSS21] Like
keywords, unit identifiers are case-insensitive within the ASCII range.
Properties may restrict the length value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
While some properties allow negative length values, this may complicate the formatting and there may be implementation-specific limits. If a negative length value is allowed but cannot be supported, it must be converted to the nearest value that can be supported.
In cases where the used length cannot be supported, user agents must approximate it in the actual value.
There are two types of length units: relative and absolute.
Relative length units specify a length relative to another length. Style sheets that use relative units can more easily scale from one output environment to another.
The relative units are:
unit | relative to |
---|---|
‘em ’
| font size of the element |
‘ex ’
| x-height of the element's font |
‘ch ’
| width of the "0" glyph in the element's font |
‘rem ’
| font size of the root element |
‘vw ’
| viewport's width |
‘vh ’
| viewport's height |
‘vm ’
| minimum of the viewport's height and width |
Child elements do not inherit the relative values as specified for their parent; they inherit the computed values.
em
’, ‘ex
’, ‘ch
’, ‘rem
’ unitsAside from ‘rem
’ (which refers to the font-size of the root
element), the font-relative lengths refer to the computed font metrics of
the element on which they are used. The exception is when they occur in
the value of the ‘font-size
’
property itself, in which case they refer to the font metrics of the
parent element (or the font metrics corresponding to the initial values of
the ‘font
’ property, if the
element has no parent).
Equal to the computed value of the ‘font-size
’ property of the element on which
it is used.
The rule:
h1 { line-height: 1.2em }
means that the line height of h1
elements will be 20%
greater than the font size of h1
element. On the other
hand:
h1 { font-size: 1.2em }
means that the font size of h1
elements will be 20%
greater than the font size inherited by h1
elements.
Equal to the font's x-height. 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.
Equal to the advance measure of the "0" (ZERO, U+0030) glyph found in the font used to render it.
Equal to the computed value of ‘font-size
’ on the root element.
When specified on the ‘font-size
’ property of the root element, the
‘rem
’ units
refer to the property's initial value.
vw
’, ‘vh
’, ‘vm
’ unitsThe viewport-relative lengths are relative to the size of the initial containing block. When the height or width of the viewport is changed, they are scaled proportionally.
In the example below, if the width of the viewport is 200mm, the font
size of h1
elements will be 16mm (i.e.
(8×200mm)/100).
h1 { font-size: 8vw }
vw
’ or ‘vh
’.
Do we need this now that we have the min() function?
Note that Paged Media defines how the initial containing block transforms across varying page widths. This also affects these units.
cm
’, ‘mm
’, ‘in
’,
‘pt
’, ‘pc
’, ‘px
’ unitsThe absolute length units are fixed in relation to each other and anchored to some physical measurement. They are mainly useful when the output environment is known. The absolute units consist of the physical units (in, cm, mm, pt, pc) and the px unit:
unit | definition |
---|---|
‘cm ’
| centimeters |
‘mm ’
| millimeters |
‘in ’
| inches; 1in is equal to 2.54cm |
‘px ’
| pixels; 1px is equal to 1/96th of 1in |
‘pt ’
| points; 1pt is equal to 1/72nd of 1in |
‘pc ’
| picas; 1pc is equal to 12pt |
h1 { margin: 0.5in } /* inches */ h2 { line-height: 3cm } /* centimeters */ h3 { word-spacing: 4mm } /* millimeters */ h4 { font-size: 12pt } /* points */ h4 { font-size: 1pc } /* picas */ p { font-size: 12px } /* px */
For a CSS device, these dimensions are either anchored (i) by relating the physical units to their physical measurements, or (ii) by relating the pixel unit to the reference pixel. For print media and similar high-resolution devices, the anchor unit should be one of the standard physical units (inches, centimeters, etc). For lower-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 that 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 that this definition of the pixel unit and the physical units differs from previous versions of CSS. In particular, in previous versions of CSS the pixel unit and the physical units were not related by a fixed ratio: the physical units were always tied to their physical measurements while the pixel unit would vary to most closely match the reference pixel. (This change was made because too much existing content relies on the assumption of 96dpi, and breaking that assumption breaks the content.)
The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is therefore about 0.0213 degrees. For reading at arm's length, 1px thus corresponds to about 0.26 mm (1/96 inch).
The image below illustrates the effect of viewing distance on the size of a reference pixel: a reading distance of 71 cm (28 inches) results in a reference pixel of 0.26 mm, while a reading distance of 3.5 m (12 feet) results in a reference pixel of 1.3 mm.
Showing that pixels must become larger if the viewing distance increases
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).
Showing that more device pixels (dots) are needed to cover a 1px by 1px area on a high-resolution device than on a low-res one
<angle>
’ type
and ‘deg
’, ‘grad
’, ‘rad
’, ‘turn
’ unitsAngle values are dimensions denoted by <angle>. The angle unit identifiers are:
For example, a right angle is ‘90deg
’
or ‘100grad
’ or ‘0.25turn
’ or approximately ‘1.570796326794897rad
’.
<time>
’ type and
‘s
’, ‘ms
’ unitsTime values are dimensions denoted by <time>. The time unit identifiers are:
Properties may restrict the time value to some range. If the value is outside the allowed range, the declaration is invalid and must be ignored.
<frequency>
’ type and ‘Hz
’, ‘kHz
’ unitsFrequency values are dimensions denoted by <frequency>. The frequency unit identifiers are:
For example, when representing sound pitches, 200Hz (or 200hz) is a bass sound, and 6kHz (or 6khz) is a treble sound.
Some data types are defined in their own modules. The two common ones
are <color>
and <image>
.
<color>
’ typeThe <color>
data type is defined in
[CSS21] and extended in [CSS3COLOR].
UAs that support CSS Color Level 3 must interpret <color>
as defined therein.
<image>
’ typeThe <image>
data type is
defined herein as equivalent to <url>
. It is extended in [CSS3-IMAGES]: UAs that support
CSS Image Values Level 3 must interpret <image>
as defined therein.
<fraction>
’ type and ‘fr
’ unitThe fr unit is used to represent proportions, such as the proportions used to distribute remaining space in a flex layout computation. [CSS3-FLEXBOX] When multiple fractions participate in a calculation, the remainder is distributed proportionally to their numeric value.
border-parts: 10px 1fr 10px; border-parts: 10px 1fr 10px 1fr 10px; border-parts: 10px 2fr 10px 2fr 10px;
<grid>
’ type and ‘gr
’ unitA grid is a set of invisible vertical and horizontal lines that can be
used to align content. In CSS, grid lines can be established implicitly
(as in [CSS3COL])
or explicitly (as in [CSS3GRID]). In either case, the
distance between grid lines can be referred to by the ‘gr
’ unit.
img { float: top left multicol; float-offset: 2gr; width: 1gr; }
Grid lines can be laid out in uneven patterns. Therefore, the ‘gr
’ unit is not linear.
For example, "2gr" is not necessarily twice as long as "1gr".
Some values use a functional notation
to type values and to and lump values together. The syntax starts with the
name of the function immediately followed by a left parenthesis followed
by optional whitespace followed by the argument(s) to the notation
followed by optional whitespace followed by a right parenthesis. If a
function takes a list of arguments, the arguments are separated by a comma
(‘,
’) with optional whitespace before
and after the comma.
background: url(http://www.example.org/image); color: rgb(100, 200, 50 ); content: counter(list-item) ". "; width: calc(50% - 2em);
calc()
’,
‘min()
’ and
‘max()
’The calc(), min(), and max() functions allow mathematical expressions with addition
(‘+
’), subtraction (‘-
’), multiplication (‘*
’), and division (‘/
’) to be used as component values. The ‘calc()
’ expression
represents the result of the mathematical calculation it contains, using
standard operator precedence rules. The ‘min()
’ and ‘max()
’ expressions represent the minimum and
maximum, respectively, of their comma-separated arguments. These
expressions can be used wherever <length>
, <frequency>
, <angle>
, <time>
, or <number>
values are allowed.
section { float: left; margin: 1em; border: solid 1px; width: calc(100%/3 - 2*1em - 2*1px); }
p { margin: calc(1rem - 2px) calc(1rem - 1px); }
p { font-size: min(10px, 3em) } blockquote { font-size: max(30px, 3em) }
.box { width: min(10% + 20px, 300px) }
Add less trivial examples, particularly involving parens or nesting.
The expression language of these functions is described by the grammar and prose below.
math : [ calc | min | max ] S*; calc : "calc(" S* sum S* ")"; min : "min(" S* sum [ "," S* sum ]* S* ")"; max : "max(" S* sum [ "," S* sum ]* S* ")"; sum : product [ S+ [ "+" | "-" ] S+ product ]*; product : unit [ S* [ "*" | "/" ] S* unit ]*; unit : ["+"|"-"]? [ NUMBER | DIMENSION | PERCENTAGE | min | max | "(" S* sum S* ")" ];
Note that the grammar requires spaces around binary
‘+
’ and ‘-
’ operators. The ‘*
’ and ‘/
’
operators do not require spaces.
Additionally, the following redefinition is made to the informative grammar appearing in CSS 2.1 Appendix G:
term : unary_operator? [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* | TIME S* | FREQ S* ] | STRING S* | IDENT S* | URI S* | hexcolor | function | math ;
A math expression has a resolved type, which
is one of ‘<length>
’, ‘<frequency>
’, ‘<angle>
’, ‘<time>
’, or ‘<number>
’. The resolved type must be valid for where the
expression is placed; otherwise, the expression is invalid. The resolved type of the expression is
determined by the types of the values it contains. NUMBER
tokens are of type ‘<number>
’. A DIMENSION
token's type is given by its
unit (‘cm
’ is ‘<length>
’, ‘deg
’ is ‘<angle>
’, etc.). If percentages are accepted in
the context in which the expression is placed, a PERCENTAGE
token has the type of the
value that percentages are relative to; otherwise, a math expression
containing percentages is invalid.
Operators form sub-expressions, which gain types based on their arguments. To make expressions simpler, operators have restrictions on the types they accept. At each operator, the types of the left and right argument are checked for these restrictions. If compatible, the type resolves as described below (the following ignores precedence rules on the operators for simplicity):
,
’, ‘+
’, or ‘-
’,
check that both sides have the same type; resolve to that type.
*
’, check that at least one
side is ‘<number>
’; resolve to the
type of the other side
/
’, check that the right side
is ‘<number>
’; resolve to the type
of the left side.
If an operator does not pass the above checks, the expression is invalid. Also, division by zero is invalid. This includes both dividing by the literal number zero, as well as any numeric expression that evaluates to zero (as purely-numeric expressions can be evaluated without any additional information at parse time).
The value resulting from an expression must be clamped to the range allowed in the target context.
Note this requires all contexts accepting ‘calc()
’ to define their
allowable values as a closed (not open) interval.
These two are equivalent to ‘width:
0px
’ since widths smaller than 0px are not allowed.
width: calc(5px - 10px); width: 0px;
Given the complexities of width and height calculations on table cells
and table elements, math expressions involving percentages for widths and
heights on table columns, table column groups, table rows, table row
groups, and table cells in both auto and fixed layout tables MAY be
treated as if ‘auto
’ had been
specified.
cycle()
’The cycle() expression allows descendant
elements to cycle over a list of values instead of inheriting the same
value. The syntax of the ‘cycle()
’ expression is:
cycle( <value># )
where <value>
is a CSS value that is valid where the
expression is placed. If any of the values inside are not valid, then the
entire ‘cycle()
’ expression is invalid.
The value returned by ‘cycle()
’ must be determined by comparing the
inherited value I (the computed value on the parent, or, for
the root, the initial value) to the computed values
Cn returned by the n-th argument to
‘cycle()
’.
For the earliest Cn such that
Cn = I, the value returned by cycle is
Cn+1. However, if this Cn is
the last value, or if there are no Cn that equal
I, the computed value of the first value is returned instead.
Note that ‘cycle()
’ explicitly looks at the computed value
of the parent, so it is useful even for non-inherited properties. This is
similar to the ‘inherit
’ keyword, which
is useful even for non-inherited properties.
/* make em elements italic, but make them normal if they're inside something that's italic */ em { font-style: cycle(italic, normal); }
/* cycle between markers for nested lists, so that the top level has disk markers, but nested lists use circle, square, box, and then (for the 5th list deep) repeat */ ul { list-style-type: disk; } li > ul { list-style-type: cycle(disk, circle, square, box); }
The ‘cycle()
’ notation is not allowed to be nested;
nor may it contain ‘attr()
’, ‘calc()
’, ‘min()
’, or ‘max()
’ notations. Declarations containing such
constructs are invalid.
attr()
’The attr() function returns the value of an attribute on the element for use as a value in a property. If used on a pseudo-element, it returns the value of the attribute on the pseudo-element's originating element.
In CSS2.1 [CSS21],
the ‘attr()
’
expression always returns a string. In CSS3, the ‘attr()
’ expression can
return many different types. The ‘attr()
’ expression cannot return everything,
for example it cannot do counters, named strings, quotes, or values such
as ‘auto
’, ‘nowrap
’, or ‘baseline
’. This is intentional, as the intent of
the ‘attr()
’
expression is not to make it possible to describe a presentational
language's formatting using CSS, but to enable CSS to take semantic data
into account.
The new syntax for the ‘attr()
’ expression is:
'attr(' wqname [ ',' <type> [ ',' <value> ]? ]? ')'
where wqname is a CSS qualified name [[!CSSNAMESPACE]] and whose syntax is defined as:
wqname : [ [ namespace_prefix? | '*' ] '|' ident ] | ident ;
The wqname argument represents an attribute
name. The computed value of the ‘attr()
’ expression is the value of the
attribute with that name on the element, according to the rules given
below.
The ‘<type>
’ argument (which is
optional but must be present if the third argument is present) is a
keyword drawn from the list below that tells the UA how to interpret the
attribute value. If omitted, ‘string
’
is implied. If the type is not valid for where the ‘attr()
’ expression is
placed, the whole ‘attr()
’ expression is invalid.
The ‘<value>
’ argument (which is
optional) is a CSS value which must be valid where the ‘attr()
’ expression is
placed. It represents a fallback value to be used if the named attribute
is missing, or its value cannot be parsed into the given type or is
invalid/out-of-range for the property. If the ‘<value>
’ argument is not valid for the property
where the ‘attr()
’ expression is placed, the whole
‘attr()
’
expression is invalid. The fallback value must not be another ‘attr()
’ expression; if
it is, the outer ‘attr()
’ expression is invalid. If the fallback
‘<value>
’ is absent, the default
value for the given type (from the list below) is implied.
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
‘5em
’.
The ‘<type>
’ keywords are:
string
’
<string>
’. The default is the
empty string.
color
’
<color>
’ value. The default is ‘currentColor
’.
url
’
url()
’ expression. The
default is a UA-dependent URI defined to point to a non-existent document
with a generic error condition. (i.e. it shouldn't be an FTP URI that
causes a DNS error, or an HTTP URI that results in a 404, it should be a
nondescript error condition.)
integer
’
<integer>
’. The default is ‘0
’. The default should also be used if the
property in question only accepts integers within a certain range and the
attribute is out of range.
number
’
<number>
’. The default is ‘0.0
’. The default should also be used if the
property in question only accepts numbers within a certain range and the
attribute is out of range.
length
’
angle
’
time
’
frequency
’
<length>
’, ‘<angle>
’, ‘<time>
’ or ‘<frequency>
’ (respectively), and the unit
identifier (if any) will appear in the attribute value. The default is
‘0
’ in the relevant units. The default
should also be used if the property in question only accepts values
within a certain range (e.g. positive lengths or angles from 0 to 90deg)
and the attribute is out of range (e.g. a negative length or 180deg).
em
’
ex
’
px
’
gr
’
rem
’
vw
’
vh
’
vm
’
mm
’
cm
’
in
’
pt
’
pc
’
deg
’
grad
’
rad
’
ms
’
s
’
Hz
’
kHz
’
%
’
<number>
’, with the given type suffixed as a
unit. The default is ‘0
’ in the
relevant units.
Ideally, it shouldn't be necessary to specify the type if it
is obvious. For example, this should be valid: ‘background-image: attr(href);
’. This could be
described as: "If the property only accepts one type of value (aside from
‘inherit
’ and ‘initial
’), that type is implied".
This example shows the use of attr() to visually illustrate data in an XML file:
<stock> <wood length="12"/> <wood length="5"/> <metal length="19"/> <wood length="4"/> </stock> stock::before { display: block; content: "To scale, the lengths of materials in stock are:"; } stock > * { display: block; width: attr(length, em); /* default 0 */ height: 1em; border: solid thin; margin: 0.5em; } wood { background: orange url(wood.png); } metal { background: silver url(metal.png); } /* this also uses a possible extension to the 'content' property to handle replaced content and alternatives to unavailable, corrupted or unsupported content */ img { content: replaced attr(src, url), attr(alt, string, none); height: attr(height, px, auto); width: attr(width, px, auto); }
All of the following examples are invalid and would cause a parse-time error, and thus cause the relevant declaration—in this case all of them—to be ignored:
content: attr(title, color); /* 'content' doesn't accept colors */ content: attr(end-of-quote, string, inherit) close-quote; /* the 'inherit' value is not allowed there, since the result would be 'inherit close-quote', which is invalid. */ margin: attr(vertical, length) attr(horizontal, deg); /* deg units are not valid at that point */ color: attr(color); /* 'color' doesn't accept strings */
The ‘attr()
’ expression cannot currently fall back
onto another attribute. Future versions of CSS may extend ‘attr()
’ in this
direction.
Shouldn't this section move to [CSS3CASCADE]?
Once a user agent has parsed a document and constructed a document tree, it must assign, for every element in the tree, a value to every property that applies to the target media type.
The final value of a CSS3 property for a given element is the result of a four-step calculation:
The specified value is the output of the cascading and inheritance process. [CSS21] [CSS3CASCADE]
If the output of the cascade is ‘inherit
’ or ‘initial
’, the specified value contains the
inherited or initial value, respectively. See examples (d) and (e) in the
table below.
The cascading and inheritance process guarantees that a specified value exists for every property on every element.
A specified value can be either
absolute (i.e., not relative to another value, as in ‘red
’ or ‘2mm
’) or relative (i.e., relative to another value,
as in ‘auto
’, ‘2em
’).
For absolute values, no extra processing is needed to find the computed
value. For relative values, on the other hand, computation is necessary to
find the computed value: percentages must be multiplied by a reference
value (each property defines which value that is), values with relative
units (em, ex, vh, vw) must be made absolute by multiplying with the
appropriate reference size, certain keywords (e.g., ‘smaller
’, ‘bolder
’) must be replaced according to their
definitions, and valid relative URLs must be resolved to become absolute.
See examples (f), (g) and (h) in the table
below.
The computed value is the result of resolving the specified value insofar as possible without formatting the document, as defined in the "Computed value" line of the property definition tables.
The computed value is the value that is transferred from parent to child during inheritance.
The computed value exists even when the property does not apply (as
defined by the ‘Applies To
’ line).
However, some properties may define the computed value of a property for
an element to depend on whether the property applies to that element.
Computed values are processed as far as possible without formatting the document. Some values, however, can only be determined when the document is being laid out. For example, if the width of an element is set to be a certain percentage of its containing block, the width cannot be determined until the width of the containing block has been determined. The used value is the result of taking the computed value and resolving any remaining dependencies into an absolute value.
A used value is in principle ready to
be used, but a user agent may not be able to make use of the value in a
given environment. For example, a user agent may only be able to render
borders with integer pixel widths and may therefore have to approximate
the computed width. Also, the font size of an element may need adjustment
based on the availability of fonts or the value of the ‘font-size-adjust
’ property. The actual value is the used value after any such
approximations have been made.
By probing the actual values of elements, much can be
learned about how the document is laid out. However, not all information
is recorded in the actual values. For example, the actual value of the
‘page-break-after
’ property does
not reflect whether there is a page break or not after the element.
Similarly, the actual value of ‘orphans
’ does not reflect how many orphan
lines there is in a certain element. See examples (j) and (k) in the table below.
Property | Winning declaration | Specified value | Computed value | Used value | Actual value | |
---|---|---|---|---|---|---|
(a) | ‘text-align ’
| text-align: left
| ‘left ’
| ‘left ’
| ‘left ’
| ‘left ’
|
(b) | ‘border-top-width ’,
‘border-right-width ’,
‘border-bottom-width ’,
‘border-left-width ’
| border-width: inherit
| ‘4.2px ’
| ‘4.2px ’
| ‘4.2px ’
| ‘4px ’
|
(c) | ‘width ’
| (none) | ‘auto ’
(initial value)
| ‘auto ’
| ‘120px ’
| ‘120px ’
|
(d) | ‘list-style-position ’
| list-style-position: inherit
| ‘inside ’
| ‘inside ’
| ‘inside ’
| ‘inside ’
|
(e) | ‘list-style-position ’
| list-style-position: initial
| ‘outside ’
(initial value)
| ‘outside ’
| ‘outside ’
| ‘outside ’
|
(f) | ‘font-size ’
| font-size: 1.2em
| ‘1.2em ’
| ‘14.1px ’
| ‘14.1px ’
| ‘14px ’
|
(g) | ‘width ’
| width: 80%
| ‘80% ’
| ‘80% ’
| ‘354.2px ’
| ‘354px ’
|
(h) | ‘width ’
| width: auto
| ‘auto ’
| ‘auto ’
| ‘134px ’
| ‘134px ’
|
(i) | ‘height ’
| height: auto
| ‘auto ’
| ‘auto ’
| ‘176px ’
| ‘176px ’
|
(j) | ‘page-break-after ’
| (none) | ‘auto ’
(initial value)
| ‘auto ’
| ‘auto ’
| ‘auto ’
|
(k) | ‘orphans ’
| orphans: 3
| ‘3 ’
| ‘3 ’
| ‘3 ’
| ‘3 ’
|
Comments and suggestions from Giovanni Campagna, Christoph Päper, Keith Rarick, Alex Mogilevsky, Ian Hickson, David Baron, Edward Welbourne, Boris Zbarsky, Björn Höhrmann and Michael Day improved this module.
<color>
, 7.1.
<identifier>
, 3.2.
<image>
, 7.2.
inherit
’, 3.1.1.
initial
’, 3.1.1.
<integer>
, 4.1.
<length>
, 5.
<number>
, 4.2.
<percentage>
, 4.3.
<string>
, 3.3.
<url>
, 3.4.