Abstract
CSSOM defines APIs (including generic parsing and serialization rules) for Media Queries, Selectors, and of course CSS itself.
Status of This Document
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than 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 “cssom” in the subject, preferably like this: “[csom] …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.
Implementers should note well that this specification is an ongoing effort to sort out what has been widely implemented and deployed from [DOM2STYLE] as well as common extensions thereto, some details of which are currently interoperable and others which are not currently interoperable. As this specification moves forward, it is hoped that these differences will be resolved and an unambiguous and adequate consensus-based specification will emerge.
Table of Contents
1 Introduction
This document formally specifies the core features of the CSS Object Model (CSSOM). Other documents in the CSSOM family of specifications as well as other CSS related specifications define extensions to these core features.
The core features of the CSSOM are oriented towards providing basic capabilities to author-defined scripts to permit access to and manipulation of style related state information and processes.
The features defined below are fundamentally based on prior specifications of the W3C DOM Working Group, primarily [DOM2STYLE]. The purposes of the present document are (1) to improve on that prior work by providing more technical specificity (so as to improve testability and interoperability), (2) to deprecate or remove certain less-widely implemented features no longer considered to be essential in this context, and (3) to newly specify certain extensions that have been or expected to be widely implemented.
2 Conformance
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and terminate these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.
When a method or an attribute is said to call another method or attribute, the user agent must invoke its internal API for that attribute or method so that e.g. the author can't change the behavior by overriding attributes or methods with custom properties or functions in ECMAScript.
Unless otherwise stated, string comparisons are done in a case-sensitive manner.
3 Terminology
This specification employs certain terminology from the following documents: DOM, HTML, CSS Syntax, URL, Fetch, Associating Style Sheets with XML documents and XML. [DOM] [HTML] [CSSSYNTAX] [URL] [FETCH] [XMLSS] [XML]
When this specification talks about object
A where A is actually an interface, it generally means an object implementing interface
A.
The terms whitespace and ignored are defined in CSS. [CSS]
The terms cascaded value, computed value and used value are defined in CSS Cascade and Inheritance. [CSSCASCADE]
The terms simple selector, sequence of simple selectors, universal selector and group of selectors are defined in Selectors. [SELECTORS]
The terms namespace prefix and default namespace are defined in CSS Namespaces Module. [CSSNAMESPACES]
The term list of CSS page selectors refers to the comma-separated list of page selectors, as defined in CSS Paged Media Module. [CSSPAGE]
The terms set and unset to refer to the true and false values of binary flags or variables, respectively. These terms are also used as verbs in which case they refer to mutating some value to make it true or false, respectively.
The term supported styling language refers to CSS.
If another styling language becomes supported in user agents, this specification is expected to be updated as necessary.
The term supported CSS property refers to a CSS property that the user agent implements, and that is defined to be a case-insensitive property in the CSS specification. A supported CSS property must be in its lowercase form for the purpose of comparisons this specification.
The term author-defined CSS property refers to var-* properties as defined in CSS Custom Properties for Cascading Variables,
and are case-sensitive. [CSSVARIABLES]
The terms ::before pseudo-element and ::after pseudo-element refer to the :before and :after pseudo-elements in CSS, except in this specification the pseudo-elements are assumed to exist for all elements even if no box is generated for them. [CSS]
3.1 Common Serializing Idioms
To escape a character means to create a string of
"\" (U+005C), followed by the character.
To escape a character as code point means to create a
string of "\" (U+005C), followed by the Unicode code point as
the smallest possible number of hexadecimal digits in the range 0-9 a-f
(U+0030 to U+0039 and U+0061 to U+0066) to represent the code point in
base 16, followed by a single SPACE (U+0020).
To serialize an identifier means to create a string represented by the concatenation of, for each character of the identifier:
- If the character is NULL (U+0000), then throw an
InvalidCharacterErrorexception and terminate these steps. - If the character is in the range [\1-\1f] (U+0001 to U+001F) or [\7f-\9f] (U+007F to U+009F), then the character escaped as code point.
- If the character is the first character and is in the range [0-9] (U+0030 to U+0039), then the character escaped as code point.
- If the character is the second character and is in the range [0-9]
(U+0030 to U+0039) and the first character is a "
-" (U+002D), then the character escaped as code point. - If the character is the second character and is "
-" (U+002D) and the first character is "-" as well, then the escaped character. - If the character is not handled by one of the above rules and is
greater than or equal to U+0080, is "
-" (U+002D) or "_" (U+005F), or is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to U+005A), or [a-z] (U+0061 to U+007A), then the character itself. - Otherwise, the escaped character.
To serialize a string means to create a string represented by '"' (U+0022), followed by the result of applying the rules below to each character of the given string, followed by '"' (U+0022):
- If the character is NULL (U+0000), then throw an
InvalidCharacterErrorexception and terminate these steps. - If the character is in the range [\1-\1f] (U+0001 to U+001F) or [\7f-\9f] (U+007F to U+009F), the character escaped as code point.
- If the character is '"' (U+0022) or "
\" (U+005C), the escaped character. - Otherwise, the character itself.
"'" (U+0027) is not escaped because strings
are always serialized with '"' (U+0022).
To serialize a URL means to create a string represented by
"url(", followed by the
string escaped value of the given
string, followed by ")".
To serialize a comma-separated list concatenate all items of
the list in list order while separating them by ", ", i.e.,
COMMA (U+002C) followed by a single SPACE (U+0020).
To serialize a whitespace-separated list concatenate all
items of the list in list order while separating them by " ", i.e.,
a single SPACE (U+0020).
When serializing a list according to the above rules, extraneous whitespace is not inserted prior to the first item or subsequent to the last item. Unless otherwise specified, an empty list is serialized as the empty string.
Media queries are defined by the Media Queries specification. This section defines various concepts around media queries, including their API and serialization form.
To parse a media query list for a given string s into a media query list is defined in the Media Queries specification. Return the list of one or more media queries that the algorithm defined there gives.
A media query that ends up being "ignored" will turn
into "not all".
To parse a media query for a given string s means to follow the parse a media query list steps and return null if more than one media query is returned or a media query if a single media query is returned.
Again, a media query that ends up being "ignored" will
turn into "not all".
To serialize a media query list run these steps:
If the media query list is empty return the empty string and terminate these steps.
Serialize each media query in the list of media queries, in the same order as they appear in the list of media queries, and then serialize the list.
To serialize a media query let s be the empty string, run the steps below, and finally return s:
If the media query is negated append "
not", followed by a single SPACE (U+0020), to s.Let type be the media type of the media query, escaped and converted to ASCII lowercase.
If the media query does not contain media features append type, to s, then return s and terminate this algorithm.
If type is not "
all" or if the media query is negated append type, followed by a single SPACE (U+0020), followed by "and", followed by a single SPACE (U+0020), to s.Sort the media features in lexicographical order.
-
Then, for each media feature:
Append a "
(" (U+0028), followed by the media feature name, converted to ASCII lowercase, to s.If a value is given append a "
:" (U+003A), followed by a single SPACE (U+0020), followed by the serialized media feature value, to s.Append a "
)" (U+0029) to s.If this is not the last media feature append a single SPACE (U+0020), followed by "
and", followed by a single SPACE (U+0020), to s.
Here are some examples of input (first column) and output (second column):
| Input | Output |
|---|---|
not screen and (min-WIDTH:5px) AND (max-width:40px) | not screen and (max-width: 40px) and (min-width: 5px) |
all and (color) and (color) | (color) |
This should probably be done in terms of mapping it to serializing CSS values as media features are defined in terms of CSS values after all.
To serialize a media feature value named v locate v in the first column of the table below and use the serialization format described in the second column:
| Media Feature | Serialization |
|---|---|
| 'width' | ... |
| 'height' | ... |
| 'device-width' | ... |
| 'device-height' | ... |
| 'orientation' |
If the value is 'portrait': " If the value is 'landscape': " |
| 'aspect-ratio' | ... |
| 'device-aspect-ratio' | ... |
| 'color' | ... |
| 'color-index' | ... |
| 'monochrome' | ... |
| 'resolution' | ... |
| 'scan' |
If the value is 'progressive': " If the value is 'interlace': " |
| 'grid' | ... |
Other specifications can extend this table and vendor-prefixed media features can have custom serialization formats as well.
To compare media queries m1 and m2 means to serialize them both and return true if they are a case-sensitive match and false if they are not.
An object that implements the MediaList interface has an associated collection of media queries.
[ArrayClass]
interface MediaList {
[TreatNullAs=EmptyString] stringifier attribute DOMString mediaText;
readonly attribute unsigned long length;
getter DOMString? item(unsigned long index);
void appendMedium(DOMString medium);
void deleteMedium(DOMString medium);
};
The object's supported property indices are the numbers in the range zero to one less than the number of media queries in the collection of media queries represented by the collection. If there are no such media queries, then there are no supported property indices.
To create a MediaList object with a string text, run the following steps:
Create a new
MediaListobject.Set its
mediaTextattribute to text.Return the newly created
MediaListobject.
The mediaText attribute, on getting, must return a
serialization of the collection of media queries.
Setting the mediaText attribute must run these steps:
Empty the collection of media queries.
If the given value is the empty string terminate these steps.
Append all the media queries as a result of parsing the given value to the collection of media queries.
The item(index) method must return the media query in the collection of media
queries given by index, or null, if index is greater than or equal to the number of media queries in the
collection of media queries.
The length attribute must return the number of media queries in the collection of media
queries.
The appendMedium(medium) method must run these steps:
Let m be the result of parsing the given value.
If m is null terminate these steps.
If comparing m with any of the media queries in the collection of media queries returns true terminate these steps.
Append m to the collection of media queries.
The deleteMedium(medium) method must run these steps:
Let m be the result of parsing the given value.
If m is null terminate these steps.
Remove any media query from the collection of media queries for which comparing the media query with m returns true.
5 Selectors
Selectors are defined in the Selectors specification. This section mainly defines how to serialize them.
5.1 Parsing Selectors
To
parse a group of selectors
means to parse the value using the selectors_group
production defined in the Selectors specification and return either a
group of selectors if parsing did not fail or null if parsing did
fail.
5.2 Serializing Selectors
To serialize a group of selectors serialize each selector in the group of selectors and then serialize the group.
To serialize a selector let s be the empty string, run the steps below for each part of the chain of the selector, and finally return s:
If there is only one simple selector in the sequence of simple selectors which is a universal selector, append the result of serializing the universal selector to s.
Otherwise, for each simple selector in the sequence of simple selectors that is not a universal selector of which the namespace prefix maps to a namespace that is not the default namespace serialize the simple selector and append the result to s.
If this is not the last part of the chain of the selector append a single SPACE (U+0020), followed by the combinator "
>", "+", or "~" as appropriate, followed by another single SPACE (U+0020) if the combinator was not whitespace, to s.If this is the last part of the chain of the selector and there is a pseudo-element, append "
::" followed by the name of the pseudo-element, to s.
To serialize a simple selector let s be the empty string, run the steps below, and finally return s:
- type selector
- universal selector
-
If the namespace prefix maps to a namespace that is not the default namespace and is not the null namespace (not in a namespace) append the escaped namespace prefix, followed by a "
|" (U+007C) to s.If the namespace prefix maps to a namespace that is the null namespace (not in a namespace) append "
|" (U+007C) to s.If this is a type selector append the escaped element name to s.
If this is a universal selector append "
*" (U+002A) to s.
- attribute selector
-
Append "
[" (U+005B) to s.If the namespace prefix maps to a namespace that is not the null namespace (not in a namespace) append the escaped namespace prefix, followed by a "
|" (U+007C) to s.Append the escaped attribute name to s.
If there is an attribute value specified, append "
=", "~=", "|=", "^=", "$=", or "*=" as appropriate (depending on the type of attribute selector), followed by the string escaped attribute value, to s.Append "
]" (U+005D) to s.
- class selector
Append a "
." (U+002E), followed by the escaped class name to s.- ID selector
Append a "
#" (U+0023), followed by the escaped ID to s.- pseudo-class
-
If the pseudo-class does not accept arguments append "
:" (U+003A), followed by the name of the pseudo-class, to s.Otherwise, append "
:" (U+003A), followed by the name of the pseudo-class, followed by "(" (U+0028), followed by the value of the pseudo-class argument determined as per below, followed by ")" (U+0029), to s.:lang()The escaped value.
:nth-child():nth-last-child():nth-of-type():nth-last-of-type()The result of serializing the value using the rules for serializing <an+b>.
:not()The result of serializing the value using the rules for serializing a group of selectors.
6 CSS
6.1 CSS Style Sheets
A CSS style sheet is an abstract concept that
represents a style sheet as defined by the CSS specification. In the CSSOM a
CSS style sheet is represented as a CSSStyleSheet object. A
CSS style sheet has a number of associated state items:
- type
The literal string "
text/css".- location
Specified when created. The absolute URL of the first request of the CSS style sheet or null if the CSS style sheet was embedded. Does not change during the lifetime of the CSS style sheet.
- parent CSS style sheet
Specified when created. The CSS style sheet that is the parent of the CSS style sheet or null if there is no associated parent.
- owner node
Specified when created. The DOM node associated with the CSS style sheet or null if there is no associated DOM node.
- owner CSS rule
Specified when created. The CSS rule in the parent CSS style sheet that caused the inclusion of the CSS style sheet or null if there is no associated rule.
- media
-
Specified when created. The
MediaListobject associated with the CSS style sheet.If this property is specified to a string, the media must be set to the return value of invoking create a
MediaListobject steps for that string.If this property is specified to an attribute of the owner node, the media must be set to the return value of invoking create a
MediaListobject steps for the value of that attribute. Whenever the attribute is set, changed or removed, the media'smediaTextattribute must be set to the new value of the attribute, or to null if the attribute is absent.Changing the media's
mediaTextattribute does not change the corresponding attribute on the owner node. - title
-
Specified when created. The title of the CSS style sheet, which can be the empty string.
In the following, the title is non-empty for the first style sheet, but is empty for the second and third style sheets.
<style title="papaya whip"> body { background: #ffefd5; } </style><style title=""> body { background: orange; } </style><style> body { background: brown; } </style>If this property is specified to an attribute of the owner node, the title must be set to the value of that attribute. Whenever the attribute is set, changed or removed, the title must be set to the new value of the attribute, or to the empty string if the attribute is absent.
- alternate flag
-
Specified when created. Either set or unset. Unset by default.
The following CSS style sheets have their alternate flag set:
<?xml-stylesheet alternate="yes" title="x" href="data:text/css,…"?>
<link rel="alternate stylesheet" title="x" href="data:text/css,…">
- disabled flag
-
Either set or unset. Unset by default.
Even when unset it does not necessarily mean that the CSS style sheet is actually used for rendering.
- CSS rules
The CSS rules associated with the CSS style sheet.
- origin-clean flag
Specified when created. Either set or unset. If it is set, the API allows reading and modifying of the CSS rules.
6.1.1 The StyleSheet Interface
The StyleSheet interface represents an abstract, base style sheet.
interface StyleSheet {
readonly attribute DOMString type;
readonly attribute DOMString? href;
readonly attribute (Element or ProcessingInstruction)? ownerNode;
readonly attribute StyleSheet? parentStyleSheet;
readonly attribute DOMString? title;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
attribute boolean disabled;
};
The type attribute must return the type.
The href attribute must return the location.
The ownerNode attribute must return the owner
node.
The parentStyleSheet attribute must return the
parent CSS style sheet.
The title attribute must return the title or null if
title is the empty string.
The media attribute must return the media.
The disabled attribute, on getting, must return true if the
disabled flag
is set, or false otherwise. On setting, the disabled attribute must set the
disabled flag if the new value is true, or unset the
disabled flag otherwise.
6.1.2 The CSSStyleSheet Interface
The CSSStyleSheet interface represents a CSS style sheet.
interface CSSStyleSheet : StyleSheet { readonly attribute CSSRule? ownerRule; [SameObject] readonly attribute CSSRuleList cssRules; unsigned long insertRule(DOMString rule, unsigned long index); void deleteRule(unsigned long index); };
The ownerRule attribute must return the owner
CSS rule. If a value other than null is ever returned, then that same value must always be returned on each get access.
The cssRules attribute must follow these steps:
If the origin-clean flag is unset, throw a
SecurityErrorexception.Return a read-only, live
CSSRuleListobject representing the CSS rules.Even though the returned
CSSRuleListobject is read-only (from the perspective of client-authored script), it can nevertheless change over time due to its liveness status. For example, invoking theinsertRule()ordeleteRule()methods can result in mutations reflected in the returned object.
The insertRule(rule, index) method must run the following steps:
If the origin-clean flag is unset, throw a
SecurityErrorexception.Return the result of invoking insert a CSS rule rule in the CSS rules at index.
The deleteRule(index) method must run the following steps:
If the origin-clean flag is unset, throw a
SecurityErrorexception.Remove a CSS rule in the CSS rules at index.
6.2 CSS Style Sheet Collections
Below various new concepts are defined that are associated with each
Document object.
Each Document has an associated list of zero or more
CSS style sheets, named the
document CSS style sheets. This is
an ordered list that contains all
CSS style sheets associated with the
Document, in
tree order, with
CSS style sheets created from HTTP
Link headers first, if any, in header
order.
To create a CSS style sheet, run these steps:
Create a new CSS style sheet object and set its properties as specified.
-
Then run the add a CSS style sheet steps for the newly created CSS style sheet.
If the origin-clean flag is unset, this can expose information from the user's intranet.
To add a CSS style sheet, run these steps:
Add the CSS style sheet to the list of document CSS style sheets at the appropriate location. The remainder of these steps deal with the disabled flag.
If the disabled flag is set, terminate these steps.
If the title is not the empty string, the alternate flag is unset, and preferred CSS style sheet set name is the empty string change the preferred CSS style sheet set name to the title.
-
If any of the following is true unset the disabled flag and terminate these steps:
Set the disabled flag.
To remove a CSS style sheet, run these steps:
Remove the CSS style sheet from the list of document CSS style sheets.
Set the CSS style sheet's parent CSS style sheet, owner node and owner CSS rule to null.
A persistent CSS style sheet is a CSS style sheet from the document CSS style sheets whose title is the empty string and whose alternate flag is unset.
A CSS style sheet set is an ordered collection of one or more CSS style sheets from the document CSS style sheets which have an identical title that is not the empty string.
A CSS style sheet set name is the title the CSS style sheet set has in common.
An enabled CSS style sheet set is a CSS style sheet set of which each CSS style sheet has its disabled flag unset.
To enable a CSS style sheet set with name name, run these steps:
If name is the empty string, set the disabled flag for each CSS style sheet that is in a CSS style sheet set and terminate these steps.
Unset the disabled flag for each CSS style sheet in a CSS style sheet set whose CSS style sheet set name is a case-sensitive match for name and set it for all other CSS style sheets in a CSS style sheet set.
To select a CSS style sheet set with name name, run these steps:
enable a CSS style sheet set with name name.
Set last CSS style sheet set name to name.
A last CSS style sheet set name is a concept to determine what CSS style sheet set was last selected. Initially its value is null.
A preferred CSS style sheet set name is a concept to determine which CSS style sheets need to have their disabled flag unset. Initially its value is the empty string.
To change the preferred CSS style sheet set name with name name, run these steps:
Let current be the preferred CSS style sheet set name.
Set preferred CSS style sheet set name to name.
If name is not a case-sensitive match for current and last CSS style sheet set name is null enable a CSS style sheet set with name name.
The HTTP Default-Style header
can be used to set the preferred CSS style sheet set name
influencing which CSS style sheet set is (initially) the
enabled CSS style sheet set.
For each HTTP Default-Style
header, in header order, the user agent must
change the preferred CSS style sheet set name with name being the
value of the header.
6.2.2 The StyleSheetList Interface
The StyleSheetList interface represents an ordered collection of CSS style sheets.
[ArrayClass]
interface StyleSheetList {
getter StyleSheet? item(unsigned long index);
readonly attribute unsigned long length;
};
The object's supported property indices are the numbers in the range zero to one less than the number of CSS style sheets represented by the collection. If there are no such CSS style sheets, then there are no supported property indices.
The item(index) method must return the indexth CSS style
sheet in the collection. If there is no indexth object in the collection, then the method must return null.
The length attribute must return the number of CSS style sheets
represented by the collection.
6.2.3 Extensions to the Document Interface
partial interface Document { [SameObject] readonly attribute StyleSheetList styleSheets; attribute DOMString? selectedStyleSheetSet; readonly attribute DOMString? lastStyleSheetSet; readonly attribute DOMString? preferredStyleSheetSet; readonly attribute DOMString[] styleSheetSets; void enableStyleSheetsForSet(DOMString? name); };
The styleSheets attribute must return a StyleSheetList collection representing
the document CSS style sheets.
Because of historical IDL limitations the styleSheets attribute
used to be on a separate interface, DocumentStyle.
The selectedStyleSheetSet attribute, on getting, must run these steps:
If there is a single enabled CSS style sheet set and no other document CSS style sheets with a title that is not the empty string have the disabled flag unset, return the CSS style sheet set name of the enabled CSS style sheet set and terminate these steps.
Otherwise, if CSS style sheets from different CSS style sheet sets have their disabled flag unset, return null and terminate these steps.
-
Otherwise, return the empty string.
At this point either all CSS style sheets with a title that is not the empty string have the disabled flag set, or there are no such CSS style sheets.
On setting the
selectedStyleSheetSet
attribute these steps must be run:
If the value is null terminate this set of steps.
Otherwise, select a CSS style sheet set with the name being the value passed.
From the DOM's perspective, all views have the same
selectedStyleSheetSet.
If a user agent supports multiple views with different selected
alternative style sheets, then this attribute (and the
StyleSheet interface's
disabled attribute)
must return and set the value for the default
view.
The lastStyleSheetSet attribute must return the last CSS style sheet set name.
This attribute is initially null.
The preferredStyleSheetSet attribute must return the preferred CSS style sheet set
name.
Unlike lastStyleSheetSet,
this attribute is initially the empty string.
The styleSheetSets attribute must return a read only array of the
CSS style sheet set names of the CSS style sheet sets, in order of the
document CSS style sheets. The array is live; if the document CSS style sheets change, the array must be updated as appropriate.
The enableStyleSheetsForSet(name) method must, when invoked, run these
steps:
If name is null terminate these steps.
enable a CSS style sheet set with name name.
CSS style sheets with a
title that is the empty string are never affected by this method.
This method does not change the values of the
lastStyleSheetSet or
preferredStyleSheetSet attributes.
6.2.4 Interaction with the User Interface
The user interface of Web browsers that support style sheets
should list the style sheet titles given in the
styleSheetSets list,
showing the
selectedStyleSheetSet
as the selected style sheet set, leaving none selected if it is
null or the empty string, and selecting an extra option
"Basic Page Style" (or similar) if it is the empty string and the
preferredStyleSheetSet
is the empty string as well.
Selecting a style sheet from this list should
use the select a CSS style sheet set set of steps. This
(by definition) affects the
lastStyleSheetSet
attribute.
6.2.4.1 Persisting the selected CSS style sheet set
If a user agent persist the selected CSS style sheet set, it should use
the value of the
selectedStyleSheetSet
attribute, or if that is null, the
lastStyleSheetSet
attribute, when leaving the page (or at some other time) to determine the
set name to store. If that is null then the CSS style sheet set should not be
persisted.
When re-setting the CSS style sheet set to the persisted value (which can
happen at any time, typically at the first time the CSS style sheets are
needed for styling the document, after the <head> of
the document has been parsed, after any scripts that are not dependent on
computed style have executed), the CSS style sheet set
should be set by using the
select a CSS style sheet set set of steps as if the user had
selected the CSS style sheet set manually.
This specification does not give any suggestions on how user agents are to decide to persist the CSS style sheet set or whether or how to persist the selected CSS style sheet set across pages.
6.2.5 Examples
Thus, in the following HTML snippet:
<link rel="alternate stylesheet" title="foo" href="a"> <link rel="alternate stylesheet" title="bar" href="b"> <script> document.selectedStyleSheetSet = 'foo'; document.styleSheets[1].disabled = false; </script> <link rel="alternate stylesheet" title="foo" href="c"> <link rel="alternate stylesheet" title="bar" href="d">
...the style sheets that end up enabled are style sheets "a", "b",
and "c", the
selectedStyleSheetSet
attribute would return null,
lastStyleSheetSet
would return "foo", and
preferredStyleSheetSet
would return the empty string.
Similarly, in the following HTML snippet:
<link rel="alternate stylesheet" title="foo" href="a"> <link rel="alternate stylesheet" title="bar" href="b"> <script> var before = document.preferredStyleSheetSet; document.styleSheets[1].disabled = false; </script> <link rel="stylesheet" title="foo" href="c"> <link rel="alternate stylesheet" title="bar" href="d"> <script> var after = document.preferredStyleSheetSet; </script>
...the "before" variable will be equal to the empty string, the
"after" variable will be equal to "foo", and style sheets "a" and "c"
will be enabled. This is the case even though the first script block
sets style sheet "b" to be enabled, because upon parsing the
following <link> element, the
preferredStyleSheetSet
is set and the
enableStyleSheetsForSet()
method is called (since
selectedStyleSheetSet
was never set
explicitly, leaving
lastStyleSheetSet at
null throughout), which changes which style sheets are enabled and which
are not.
6.3 Style Sheet Association
This section defines the interface an
owner node of a CSS style sheet has to
implement and defines the requirements for
xml-stylesheet processing instructions
and HTTP Link headers when the link
relation type is an
ASCII case-insensitive match for
"stylesheet" since nobody else was interested in
defining this.
The editor is in good hope that HTML and SVG will define the appropriate processing in their respective specifications, in terms of this specification, in due course.
6.3.1 Fetching CSS style sheets
To fetch a CSS style sheet with parsed URL parsed URL, referrer referrer, document document, optionally a set of parameters parameters (used as input to creating a request), follow these steps:
Let origin be document's origin.
Let request be a new request, with the url parsed URL, origin origin, referrer referrer, and if specified the set of parameters parameters.
Let response be the result of fetching request.
Wait until response is available.
If response is a network error, return an error.
If document is in quirks mode, response is CORS-same-origin and the Content-Type metadata of response is not a supported styling language change the Content-Type metadata of response to
text/css.If response is not in a supported styling language return an error.
Return response.
6.3.2 The LinkStyle Interface
The associated CSS style sheet of a node is the CSS style sheet in the list of
document CSS style sheets of which the owner node implements the LinkStyle
interface.
[NoInterfaceObject]
interface LinkStyle {
readonly attribute StyleSheet? sheet;
};
The sheet attribute must return the associated CSS style sheet for the node or null
if there is no associated CSS style sheet.
In the following fragment, the first style
element has a sheet attribute that returns a
StyleSheet object representing the style sheet, but for
the second style element, the sheet attribute returns null,
assuming the user agent supports CSS (text/css), but does
not support the (hypothetical) ExampleSheets (text/example-sheets).
<style type="text/css">
body { background:lime }
</style>
<style type="text/example-sheets"> $(body).background := lime </style>
Whether or not the node refers to a style sheet is defined by the specification that defines the semantics of said node.
6.3.3 Requirements on specifications
Specifications introducing new ways of associating style sheets through
the DOM should define which nodes implement the
LinkStyle interface. When doing so, they
must also define when a CSS style sheet is
created.
6.3.4 Requirements on User Agents Implementing the xml-stylesheet processing instruction
ProcessingInstruction implements LinkStyle;
The prolog refers to nodes that are children of the
document and are not following the
Element child of the document, if any.
When a ProcessingInstruction node node is inserted to a
document, removed from a document, becomes part of the prolog, is no longer part of the prolog, or has its
data changed, these steps must be run:
If an instance of this algorithm is currently running for node, abort that instance, and stop the associated fetching if applicable.
If node has an associated CSS style sheet, remove it.
If node is not an xml-stylesheet processing instruction, terminate these steps.
If node is part of the document type declaration, terminate these steps.
If node does not have an
hrefpseudo-attribute, terminate these steps.Let title be the value of the
titlepseudo-attribute or the empty string if thetitlepseudo-attribute is not specified.If there is an
alternatepseudo-attribute whose value is a case-sensitive match for "yes" and title is the empty string terminate these steps.If there is a
typepseudo-attribute whose value is not a supported styling language the user agent may terminate these steps.Let input URL be the value specified by the
hrefpseudo-attribute.Let document be node's node document
Let base URL be document's document base URL.
Let referrer be document's address.
Let parsed URL be the return value of invoking the URL parser with the string input URL and the base URL base URL.
If parsed URL is failure, terminate these steps.
Let response be the result of fetching a CSS style sheet with parsed URL parsed URL, referrer referrer and document document.
If response is an error, terminate these steps.
-
Create a CSS style sheet with the following properties:
- location
The result of invoking the URL serializer with parsed URL.
- parent CSS style sheet
null.
- owner node
node.
- owner CSS rule
null.
- media
The value of the
mediapseudo-attribute if any, or the empty string otherwise.- title
title.
- alternate flag
Set if the
alternatepseudo-attribute value is a case-sensitive match for "yes", or unset otherwise.- origin-clean flag
Set if response is CORS-same-origin, or unset otherwise.
A style sheet referenced by an xml-stylesheet processing instruction using the rules in this section, in the context of
the Document of an XML parser is said to be
a style sheet that is blocking scripts if the ProcessingInstruction
node was created by that Document's parser, and the style sheet was
enabled when the node was created by the parser, and the style sheet ready flag is not yet set, and, the last time the
event loop reached step 1, the node was in that Document, and the user agent hasn't given up on that particular style sheet
yet. A user agent may give up on such a style sheet at any time.
For each HTTP Link header of which one
of the link relation types is an
ASCII case-insensitive match
for "stylesheet" these steps
must be run:
Let title be the value of the first of all the
titleparameters. If there are no such parameters it is the empty string.If one of the (other) link relation types is an ASCII case-insensitive match for "
alternate" and title is the empty string terminate these steps.Let input URL be the value specified. Be more specific
Let base URL be the document's document base URL. Is there a document at this point?
Let referrer be the document's address.
Let origin be the document's origin.
Let parsed URL be the return value of invoking the URL parser with the string input URL and the base URL base URL.
If parsed URL is failure, terminate these steps.
Let response be the result of fetching a CSS style sheet with parsed URL parsed URL, referrer referrer and document being the document. What if the HTML parser hasn't decided on quirks/non-quirks yet?
-
Create a CSS style sheet with the following properties:
- location
The result of invoking the URL serializer with parsed URL.
- owner node
null.
- parent CSS style sheet
null.
- owner CSS rule
null.
- media
The value of the first
mediaparameter.- title
title.
- alternate flag
Set if one of the specified link relation type for this HTTP
Linkheader is an ASCII case-insensitive match for "alternate", or false otherwise.- origin-clean flag
Set if response is CORS-same-origin, or unset otherwise.
A style sheet referenced by a HTTP Link header using the rules in this section is said to be a style sheet
that is blocking scripts if the style sheet was enabled when created, and the style sheet ready flag is not yet set,
and the user agent hasn't given up on that particular style sheet yet. A user agent may give up on such a style sheet at any time.
6.4 CSS Rules
A CSS rule is an abstract concept that
denotes a rule as defined by the CSS specification. A
CSS rule is represented as an object that implements a subclass of
the CSSRule interface, and which has the following
associated state items:
- type
A non-negative integer associated with a particular type of rule. This item is initialized when a rule is created and cannot change.
- text
A text representation of the rule suitable for direct use in a style sheet. This item is initialized when a rule is created and can be changed.
- parent CSS rule
A reference to an enclosing CSS rule or null. If the rule has an enclosing rule when it is created, then this item is initialized to the enclosing rule; otherwise it is null. It can be changed to null.
- parent CSS style sheet
A reference to a parent CSS style sheet or null. This item is initialized to reference an associated style sheet when the rule is created. It can be changed to null.
- child CSS rules
A list of child CSS rules. The list can be mutated.
In addition to the above state, each CSS rule may be associated with other state in accordance with its type.
To parse a CSS rule from a string string, run the following steps:
Let rule be the return value of invoking parse a rule with string.
If rule is a syntax error, return rule.
Let parsed rule be the result of parsing rule according to the appropriate CSS specifications, dropping parts that are said to be ignored. If the whole style rule is dropped, return a syntax error.
Return parsed rule.
To serialize a CSS rule, perform one of the following in accordance with the CSS rule's type:
CSSStyleRule-
The result of concatenating the following:
- The result of performing serialize a group of selectors on the rule's associated selectors.
- The string "
{", i.e., a single SPACE (U+0020), followed by LEFT CURLY BRACKET (U+007B), followed by a single SPACE (U+0020). - The result of performing serialize a CSS declaration block on the rule's associated declarations.
- If the rule is associated with one or more declarations, the string "
", i.e., a single SPACE (U+0020). - The string "
}", RIGHT CURLY BRACKET (U+007D).
CSSCharsetRule-
The result of concatenating the following:
- The string "
@charset" followed by a single SPACE (U+0020). - The result of performing serialize a string on the rule's character encoding.
- The string "
;", i.e., SEMICOLON (U+003B).
- The string "
CSSImportRule-
The result of concatenating the following:
- The string "
@import" followed by a single SPACE (U+0020). - The result of performing serialize a URL on the rule's location.
- If the rule's associated media list is not empty, a single SPACE (U+0020) followed by the result of performing serialize a media query list on the media list.
- The string "
;", i.e., SEMICOLON (U+003B).
@import url("import.css");@import url("print.css") print; - The string "
CSSMediaRule...
CSSFontFaceRule...
CSSPageRule...
CSSNamespaceRuleThe literal string "
@namespace", followed by a single SPACE (U+0020), followed by the identifier escaped value of theprefixattribute (if any), followed by a single SPACE (U+0020) if there is a prefix, followed by the URL escaped value of thenamespaceURIattribute, followed the character ";" (U+003B).
To insert a CSS rule rule in a CSS rule list list at index index, follow these steps:
Set new rule to the results of performing parse a CSS rule on argument rule.
If new rule is a syntax error, throw a
SyntaxErrorexception.If new rule is an
@charsetat-rule, throw aSyntaxErrorexception.Set length to the number of items in list.
If index is greater than length, then throw an
IndexSizeErrorexception.If new rule cannot be inserted into list at the zero-index position index due to constraints specified by CSS, then throw a
HierarchyRequestErrorexception. [CSS]For example, a CSS style sheet cannot contain an
@importat-rule after a style rule.If new rule is an
@namespaceat-rule, and list contains anything other than@charsetat-rules,@importat-rules, and@namespaceat-rules, throw anInvalidStateErrorexception.Insert new rule into list at the zero-indexed position index.
Return index.
To remove a CSS rule from a CSS rule list list at index index, follow these steps:
Set length to the number of items in list.
If index is greater than or equal to length, then throw an
IndexSizeErrorexception.Set old rule to the indexth item in list.
If old rule is an
@namespaceat-rule, and list contains anything other than@charsetat-rules,@importat-rules, and@namespaceat-rules, throw anInvalidStateErrorexception.Remove rule old rule from list at the zero-indexed position index.
Set old rule's parent CSS rule and parent CSS style sheet to null.
6.4.1 The CSSRuleList Interface
The CSSRuleList interface represents an ordered collection of CSS style rules.
[ArrayClass]
interface CSSRuleList {
getter CSSRule? item(unsigned long index);
readonly attribute unsigned long length;
};
The object's supported property indices are the numbers in the range zero to one less than the number of
CSSRule objects represented by the collection. If there are no such CSSRule objects, then there are no
supported property indices.
The item(index) method must return the indexth CSSRule
object in the collection. If there is no indexth object in the collection, then the method must return null.
The length attribute must return the number of CSSRule objects represented by the
collection.
6.4.2 The CSSRule Interface
The CSSRule interface represents an abstract, base CSS style rule. Each
distinct CSS style rule type is represented by a distinct interface that
inherits from this interface.
interface CSSRule {
const unsigned short STYLE_RULE = 1;
const unsigned short CHARSET_RULE = 2;
const unsigned short IMPORT_RULE = 3;
const unsigned short MEDIA_RULE = 4;
const unsigned short FONT_FACE_RULE = 5;
const unsigned short PAGE_RULE = 6;
const unsigned short MARGIN_RULE = 9;
const unsigned short NAMESPACE_RULE = 10;
readonly attribute unsigned short type;
attribute DOMString cssText;
readonly attribute CSSRule? parentRule;
readonly attribute CSSStyleSheet? parentStyleSheet;
};
The type attribute must return the CSS rule type, as follows:
- If the object is a
CSSStyleRule Return
STYLE_RULE(numeric value 1).- If the object is a
CSSCharsetRule Return
CHARSET_RULE(numberic value 2).- If the object is a
CSSImportRule Return
IMPORT_RULE(numberic value 3).- If the object is a
CSSMediaRule Return
MEDIA_RULE(numeric value 4).- If the object is a
CSSFontFaceRule Return
FONT_FACE_RULE(numeric value 5).- If the object is a
CSSPageRule Return
PAGE_RULE(numeric value 6).- If the object is a
CSSNamespaceRule Return
MARGIN_RULE(numeric value 9).- If the object is a
CSSMarginRule Return
NAMESPACE_RULE(numeric value 10).- Otherwise
Return a value defined on the CSSOM Constants wiki page.
The value 0, formerly known as UNKNOWN_RULE, is made
obsolete by this specification. This value will not be re-allocated in the future and will remain reserved.
The cssText attribute must return a serialization of the
CSS rule.
On setting the cssText attribute these steps must be run:
Let new rule be the returned value of parsing the value.
If new rule is a syntax error, terminate this algorithm.
If the type of new rule does not match the type of the current object throw an
InvalidModificationErrorexception.Replace the current object with new rule.
The parentRule attribute must return the parent CSS
rule.
For example, @media can enclose a rule, in which case parentRule would
be non-null; in cases where there is no enclosing rule, parentRule will be null.
The parentStyleSheet attribute must return the
parent CSS style sheet.
The only circumstance where null is returned when a rule has been removed.
Removing a Node that implements the LinkStyle interface from a
Document instance does not (by itself) cause the CSSStyleSheet referenced by a CSSRule to be
unreachable.
6.4.3 The CSSStyleRule Interface
The CSSStyleRule interface represents a style rule.
CSS 2.1 calls style rule rule sets.
interface CSSStyleRule : CSSRule { attribute DOMString selectorText; [SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style; };
The selectorText attribute, on getting, must return the result of
serializing the associated group of selectors.
On setting the selectorText attribute these steps must be run:
Run the parse a group of selectors algorithm on the given value.
If the algorithm returns a non-null value replace the associated group of selectors with the returned value.
Otherwise, if the algorithm returns a null value, do nothing.
The style attribute must return a CSSStyleDeclaration object for the style rule, with the
following properties:
- readonly flag
Unset.
- declarations
The declared declarations in the rule, in specified order.
- parent CSS rule
The context object.
- owner node
Null.
The specified order for declarations is the same as specified, but with shorthand properties expanded into their longhand properties, in canonical order. If a property is specified more than once (after shorthand expansion), only the one with greatest cascading order must be represented, at the same relative position as it was specified. [CSSCASCADE]
6.4.4 The CSSCharsetRule Interface
The CSSCharsetRule interface represents an @charset at-rule.
interface CSSCharsetRule : CSSRule { attribute DOMString encoding; };
The encoding attribute must return the encoding information specified by the
@charset at-rule.
6.4.5 The CSSImportRule Interface
The CSSImportRule interface represents an @import at-rule.
interface CSSImportRule : CSSRule { readonly attribute DOMString href; [SameObject, PutForwards=mediaText] readonly attribute MediaList media; [SameObject] readonly attribute CSSStyleSheet styleSheet; };
The href attribute must return the URL specified by
the @import at-rule.
To get the resolved URL use the href
attribute of the associated CSS style sheet.
The media attribute must return the value of the media
attribute of the associated CSS style sheet.
The styleSheet attribute must return the associated CSS style sheet.
If loading of the style sheet fails its CSS rules
list is simply empty, i.e., an @import at-rule always has an associated CSS style sheet.
6.4.6 The CSSGroupingRule Interface
The CSSGroupingRule interface represents an at-rule that contains other rules nested inside itself.
interface CSSGroupingRule : CSSRule { [SameObject] readonly attribute CSSRuleList cssRules; unsigned long insertRule(DOMString rule, unsigned long index); void deleteRule(unsigned long index); };
The cssRules attribute must return a CSSRuleList object for the
child CSS rules.
The insertRule(rule, index) method must return the result of
invoking insert a CSS rule rule into the child CSS rules at
index.
The deleteRule(index) method must remove a CSS rule from the
child CSS rules at index.
The CSSMediaRule interface represents an @media at-rule.
interface CSSMediaRule : CSSGroupingRule { [SameObject, PutForwards=mediaText] readonly attribute MediaList media; };
The media attribute must return a MediaList object for the list of media queries specified
with the @media at-rule.
The CSSPageRule interface represents an @page at-rule.
Need to define the rules for parse a list of CSS page selectors and serialize a list of CSS page selectors.
interface : CSSGroupingRule { attribute DOMString selectorText; [SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style; };
The attribute, on getting, must return the result of serializing the associated list of CSS page selectors.
On setting the selectorText attribute these steps must be run:
Run the parse a list of CSS page selectors algorithm on the given value.
If the algorithm returns a non-null value replace the associated list of CSS page selectors with the returned value.
Otherwise, if the algorithm returns a null value, do nothing.
The attribute must return a CSSStyleDeclaration object for the
@page at-rule, with the following properties:
- readonly flag
Unset.
- declarations
The declared declarations in the rule, in specified order.
- parent CSS rule
The context object.
- owner node
Null.
6.4.9 The CSSMarginRule Interface
The CSSMarginRule interface represents a margin at-rule (e.g. @top-left) in an @page at-rule.
[CSSPAGE]
interface CSSMarginRule : CSSRule { readonly attribute DOMString name; [SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style; };
The name attribute must return the name of the margin at-rule. The @ character is not
included in the name. [CSSSYNTAX]
The style attribute must return a CSSStyleDeclaration object for the
margin at-rule, with the following properties:
- readonly flag
Unset.
- declarations
The declared declarations in the rule, in specified order.
- parent CSS rule
The context object.
- owner node
Null.
6.4.10 The CSSNamespaceRule Interface
The CSSNamespaceRule interface represents an @namespace at-rule.
interface CSSNamespaceRule : CSSRule { [TreatNullAs=EmptyString] attribute DOMString namespaceURI; [TreatNullAs=EmptyString] attribute DOMString prefix; };
The namespaceURI attribute, on getting, must return the namespace of the
@namespace at-rule.
On setting, the namespaceURI attribute must run the following steps:
Let parent be the parent CSS style sheet.
Let list be the CSS rules of parent, or null if parent is null.
If list is not null and contains anything other than
@charsetat-rules,@importat-rules, and@namespaceat-rules, throw anInvalidStateErrorexception.Set the namespace of the
@namespaceat-rule to the given value.
The prefix attribute must return the prefix of the @namespace at-rule or the
empty string if there is no prefix.
On setting, the prefix attribute must run the following steps:
Let parent be the parent CSS style sheet.
Let list be the CSS rules of parent, or null if parent is null.
If list is not null and contains anything other than
@charsetat-rules,@importat-rules, and@namespaceat-rules, throw anInvalidStateErrorexception.Set the prefix of the
@namespaceat-rule to the given value.
6.5 CSS Declarations
A CSS declaration is an abstract concept that is not exposed as an object in the DOM. A CSS declaration has the following associated properties:
- property name
The property name of the declaration.
- value
The value of the declaration represented as a list of component values.
- important flag
Either set or unset. Can be changed.
- case-sensitive flag
Set if the property name is defined to be case-sensitive according to its specification, otherwise unset.
6.6 CSS Declaration Blocks
A CSS declaration block is an ordered collection of CSS
properties with their associated values, also named CSS declarations. In
the DOM a CSS declaration block is a
CSSStyleDeclaration object. A
CSS declaration block has the following associated properties:
- readonly flag
Unset if the object can be manipulated. Set if it can not be manipulated. Unless otherwise stated it is unset.
- declarations
The CSS declarations associated with the object.
- parent CSS rule
The CSS rule that the CSS declaration block is associated with, if any, or null otherwise.
- owner node
The Element or PseudoElement that the CSS declaration block is associated with, if any, or null otherwise.
To parse a CSS declaration block from a string string, follow these steps:
Let declarations be the return value of invoking parse a list of declarations with string.
Let parsed declarations be a new empty list.
For each item declaration in declarations, follow these substeps:
Let parsed declaration be the result of parsing declaration according to the appropriate CSS specifications, dropping parts that are said to be ignored. If the whole declaration is dropped, let parsed declaration be null.
If parsed declaration is not null, append it to parsed declarations.
Return parsed declarations.
To serialize a CSS declaration with property name property, value value and optionally an important flag set, follow these steps:
Let s be the empty string.
Append property to s.
Append "
:" (U+003A U+0020) to s.Append value to s.
If the important flag is set, append "
!important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072 U+0074 U+0061 U+006E U+0074) to s.Append "
;" (U+003B) to s.Return s.
To serialize a CSS declaration block declaration block means to run the steps below:
Let list be an empty array.
Let already serialized be an empty array.
Declaration loop: For each CSS declaration declaration in declaration block's declarations, follow these substeps:
Let property be declaration's property name.
If property is in already serialized, continue with the steps labeled declaration loop.
If property maps to one or more shorthand properties, let shorthands be an array of those shorthand properties, in preferred order, and follow these substeps:
Let longhands be an array consisting of all CSS declarations in declaration block's declarations that that are not in already serialized and have a property name that maps to one of the shorthand properties in shorthands.
Shorthand loop: For each shorthand in shorthands, follow these substeps:
If all properties that map to shorthand are not present in longhands, continue with the steps labeled shorthand loop.
Let current longhands be an empty array.
Append all CSS declarations in longhands have a property name that maps to shorthand to current longhands.
If there is one or more CSS declarations in current longhands have their important flag set and one or more with it unset, continue with the steps labeled shorthand loop.
Let value be the result of invoking serialize a CSS value of current longhands.
If value is the empty string, continue with the steps labeled shorthand loop.
Let serialized declaration be the result of invoking serialize a CSS declaration with property name shorthand, value value, and the important flag set if the CSS declarations in current longhands have their important flag set.
Append serialized declaration to list.
Append the property names of all items of current longhands to already serialized.
Remove the items present in current longhands from longhands.
If property is in already serialized, continue with the steps labeled declaration loop.
Let value be the result of invoking serialize a CSS value of declaration.
Let serialized declaration be the result of invoking serialize a CSS declaration with property name property, value value, and the important flag set if declaration has its important flag set.
Append serialized declaration to list.
Append property to already serialized.
Return list joined with "
" (U+0020).
The serialization of an empty CSS declaration block is the empty string.
The serialization of a non-empty CSS declaration block does not include any surrounding whitespace, i.e., no whitepsace appears before the first property name and no whitespace appears after the final semicolon delimiter that follows the last property value.
The preferred order of a list of shorthand properties shorthands is as follows:
Order shorthands lexicographically.
Move all items in shorthands that begin with "
-" (U+002D) last in the list, retaining their relative order.Move all items in shorthands that begin with "
-" (U+002D) but do not begin with "-webkit-" last in the list, retaining their relative order.Order shorthands by the number of longhand properties that map to it, with the greatest number first.
6.6.1 The CSSStyleDeclaration Interface
The CSSStyleDeclaration interface represents a CSS declaration block, including its underlying state, where this
underlying state depends upon the source of the CSSStyleDeclaration instance.
interface CSSStyleDeclaration {
attribute DOMString cssText;
readonly attribute unsigned long length;
getter DOMString item(unsigned long index);
DOMString getPropertyValue(DOMString property);
DOMString getPropertyPriority(DOMString property);
void setProperty(DOMString property, [TreatNullAs=EmptyString] DOMString value, [TreatNullAs=EmptyString] optional DOMString priority = "");
void setPropertyValue(DOMString property, [TreatNullAs=EmptyString] DOMString value);
void setPropertyPriority(DOMString property, [TreatNullAs=EmptyString] DOMString priority);
DOMString removeProperty(DOMString property);
readonly attribute CSSRule? parentRule;
attribute DOMString cssFloat;
};
The object's supported property indices are the numbers in the range zero to one less than the number of CSS declarations in the declarations. If there are no such CSS declarations, then there are no supported property indices.
The cssText attribute must return the result of
serializing the declarations.
Setting the cssText attribute must run these steps:
If the readonly flag is set, throw a
NoModificationAllowedErrorexception and terminate these steps.Empty the declarations.
Parse the given value and, if the return value is not the empty list, insert the items in the list into the declarations, in specified order.
The length attribute must return the number of CSS
declarations in the declarations.
The item(index) method must return the
property name of the CSS declaration at position index.
The getPropertyValue(property) method must run these steps:
Let property be property converted to ASCII lowercase.
If property is a shorthand property, then follow these substeps:
Let list be a new empty array.
For each longhand property longhand that property maps to, in canonical order, follow these substeps:
If longhand is a case-sensitive match for a property name of a CSS declaration in the declarations, let declaration be that CSS declaration, or null otherwise.
If declaration is null, return the empty string and terminate these steps.
Append the declaration to list.
Return the serialization of list and terminate these steps.
If property is a case-sensitive match for a property name of a CSS declaration in the declarations, return the result of invoking serialize a CSS value of that declaration and terminate these steps.
Return the empty string.
The getPropertyPriority(property) method must run these steps:
Let property be property converted to ASCII lowercase.
If property is a shorthand property, follow these substeps:
Let list be a new array.
For each longhand property longhand that property maps to, append the result of invoking
getPropertyPriority()with longhand as argument to list.If all items in list are the string "
important", return the string "important" and terminate these steps.
Otherwise, follow these substeps:
If property is a case-sensitive match for a property name of a CSS declaration in the declarations that has the important flag set, return the string "
important".
Return the empty string.
E.g. for background-color:lime !IMPORTANT the return
value would be "important".
The setProperty(property, value,
priority) method must run these steps:
If the readonly flag is set, throw a
NoModificationAllowedErrorexception and terminate these steps.Let property be property converted to ASCII lowercase.
If property is not a case-sensitive match for a supported CSS property, terminate this algorithm.
If value is the empty string, invoke
removeProperty()with property as argument and terminate this algorithm.If priority is not the empty string and is not an ASCII case-insensitive match for the string "
important", terminate this algorithm.-
Let component value list be the result of parsing value for property property.
value can not include "
!important". If component value list is null terminate these steps.
If property is a shorthand property, then for each longhand property longhand that property maps to, in canonical order, append the CSS declaration longhand with the appropriate value(s) from component value list, with the important flag set if priority is not the empty string, and unset otherwise, and with the list of declarations being the declarations.
Otherwise, append the CSS declaration property with value component value list, with the important flag set if priority is not the empty string, and unset otherwise, and with the list of declarations being the declarations.
To append a CSS declaration property with a value component value list and optionally with an important flag set, in a list of declarations declarations, follow these steps:
If property is a case-sensitive match for a property name of a CSS declaration in declarations, let declaration be that CSS declaration.
Otherwise, append a new CSS declaration with the property name property to declarations and let declaration be that CSS declaration.
If declaration has its important flag set and the important flag is not set, terminate these steps.
Set declaration's value to component value list.
If the important flag is set, set declaration's important flag.
The setPropertyValue(property, value) method must run these
steps:
If the readonly flag is set, throw a
NoModificationAllowedErrorexception and terminate these steps.Let property be property converted to ASCII lowercase.
If property is not a case-sensitive match for a supported CSS property, terminate this algorithm.
If value is the empty string, invoke
removeProperty()with property as argument and terminate this algorithm.-
Let component value list be the result of parsing value for property property.
value can not include "
!important". If component value list is null terminate these steps.
If property is a shorthand property, then for each longhand property longhand that property maps to, in canonical order, set the CSS declaration value longhand to the appropriate value(s) from component value list, and with the list of declarations being the declarations.
Otherwise, set the CSS declaration value property to the value component value list, and with the list of declarations being the declarations.
To set a CSS declaration value to a value component value list in a list of declarations declarations, follow these steps:
If property is a case-sensitive match for a property name of a CSS declaration in declarations, let declaration be that CSS declaration.
Otherwise, append a new CSS declaration with the property name property to declarations and let declaration be that CSS declaration.
Set declaration's value to component value list.
The setPropertyPriority(property, priority) method must run
these steps:
If the readonly flag is set, throw a
NoModificationAllowedErrorexception and terminate these steps.Let property be property converted to ASCII lowercase.
If property is not a case-sensitive match for a supported CSS property, terminate this algorithm.
If priority is not the empty string and is not an ASCII case-insensitive match for the string "
important", terminate this algorithm.If property is a shorthand property, then for each longhand property longhand that property maps to, in canonical order, set the CSS declaration priority longhand with the important flag set if priority is not the empty string, and unset otherwise, and with the list of declarations being the declarations.
Otherwise, set the CSS declaration priority property with the important flag set if priority is not the empty string, and unset otherwise, and with the list of declarations being the declarations.
To set a CSS declaration priority property optionally with an important flag set, in a list of declarations declarations, follow these steps:
If property is a case-sensitive match for a property name of a CSS declaration in declarations, let declaration be that CSS declaration.
Otherwise, terminate these steps.
If the important flag is set, set declaration's important flag. Otherwise, unset declaration's important flag.
The removeProperty(property) method must run these steps:
If the readonly flag is set, throw a
NoModificationAllowedErrorexception and terminate these steps.Let property be property converted to ASCII lowercase.
Let value be the return value of invoking
getPropertyValue()with property as argument.If property is a shorthand property, for each longhand property longhand that property maps to, invoke
removeProperty()with longhand as argument.Otherwise, if property is a case-sensitive match for a property name of a CSS declaration in the declarations, remove that CSS declaration.
Return value.
The parentRule attribute must return the
parent CSS rule.
The cssFloat
attribute, on getting, must return the result of invoking
getPropertyValue() with
float as argument. On setting, the attribute must invoke
setProperty() with
float as first argument, as second argument the given value, and no third argument.
Any exceptions thrown must be re-thrown.
For each CSS property property that is a supported CSS property, the following partial interface applies where camel-cased attribute is obtained by running the CSS property to IDL attribute algorithm for property.
The camel-cased attribute attribute, on getting, must return the
result of invoking getPropertyValue() with the
argument being the result of running the IDL attribute to CSS property
algorithm for camel-cased attribute.
Setting the camel-cased attribute attribute must invoke
setProperty() with the
first argument being the result of running the IDL attribute to CSS property
algorithm for camel-cased attribute, as second argument the given value, and no third argument. Any
exceptions thrown must be re-thrown.
For example, for the 'font-size' property there would be a fontSize IDL attribute.
The CSS property to IDL attribute algorithm for property is as follows:
Let output be the empty string.
Let uppercase next be unset.
For each character c in property:
If c is "
-" (U+002D), let uppercase next be set.Otherwise, if uppercase next is set, let uppercase next be unset and append c converted to ASCII uppercase to output.
Otherwise, append c to output.
Return output.
The IDL attribute to CSS property algorithm for attribute is as follows:
Let output be the empty string.
For each character c in attribute:
If c is in the range U+0041 to U+005A (ASCII uppercase), append "
-" (U+002D) followed by c converted to ASCII lowercase to output.Otherwise, append c to output.
Return output.
6.7 CSS Values
6.7.1 Parsing CSS Values
To parse a CSS value value for a given property means to follow these steps:
Let list be the value returned by invoking parse a list of component values from value.
Match list against the grammar for the property property in the CSS specification.
If the above step failed, return null.
Return list.
"!important" declarations are not
part of the property value space and will therefore cause
parse a CSS value to return null.
6.7.2 Serializing CSS Values
To serialize a CSS value of a CSS declaration declaration or a list of longhand CSS declarations list, follow these rules:
If this algorithm is invoked with a list list, follow these substeps:
Let shorthand be the shorthand property that exactly maps to all the longhand properties in list. If there are multiple such shorthand properties, use the first in preferred order.
If shorthand cannot represent the values of list in its grammar, return the empty string and terminate these steps.
Let trimmed list be a new empty array.
For each CSS declaration declaration in list, if declaration's value is not the initial value, or if declaration is a required component of the shorthand property, append declaration to trimmed list.
If trimmed list is empty, append the value of the first item in list to trimmed list.
Let values be a new empty array.
For each CSS declaration declaration in trimmed list, invoke serialize a CSS value of declaration, and append the result to values.
Return the result of joining values as appropriate according to the grammar of shorthand and terminate these steps.
Let values be a new empty array.
Append the result of invoking serialize a CSS component value of declaration's value to values.
If the grammar of the property name of declaration is defined to be whitespace-separated, return the result of invoking serialize a whitespace-separated list of values and terminate these steps.
If the grammar of the property name of declaration is defined to be comma-separated, return the result of invoking serialize a comma-separated list of values.
To serialize a CSS component value depends on the component, as follows:
- keyword
The keyword converted to ASCII lowercase.
- <angle>
The <number> component serialized as per <number> followed by the unit in canonical form as defined in its respective specification.
- <color>
-
If <color> is a component of a resolved or computed value, then return the color using the
rgb()orrgba()functional notation as follows:- If the alpha component of the color is equal to one, then return the serialization of the
rgb()functional equivalent of the opaque color. - If the alpha component of the color is not equal to one, then return the serialization of the
rgba()functional equivalent of the non-opaque color.
The serialization of the
rgb()functional equivalent is the concatenation of the following:- The string "
rgb(". - The shortest base-ten integer serialization of the color's red component.
- The string "
,". - The shortest base-ten serialization of the color's green component.
- The string "
,". - The shortest base-ten serialization of the color's blue component.
- The string "
)".
The serialization of the
rgba()functional equivalent is the concatenation of the following:- The string "
rgba(". - The shortest base-ten serialization of the color's red component.
- The string "
,". - The shortest base-ten serialization of the color's green component.
- The string "
,". - The shortest base-ten serialization of the color's blue component.
- The string "
,". - The shortest serialization of the <number> that denotes the color's alpha component.
- The string "
)".
In the above rules, the string "
," denotes a COMMA (U+002C) followed by a single SPACE (U+0020).If <color> is a component of a specified value, then return the color as follows:
- If the color was explicitly specified by the author, then return the original, author specified color value.
- Otherwise, return the value that would be returned if the color were a component of a computed value.
Should author specified values be normalized for case? Or should original case be preserved?
- If the alpha component of the color is equal to one, then return the serialization of the
- <counter>
-
The return value of the following algorithm:
Let s be the empty string.
If <counter> has three CSS component values append the string "
counters(" to s.If <counter> has two CSS component values append the string "
counter(" to s.Let list be a list of CSS component values belonging to <counter>, omitting the last CSS component value if it is 'decimal'.
Let each item in list be the result of invoking serialize a CSS component value on that item.
Append the result of invoking serialize a comma-separated list on list to s.
Append "
)" (U+0029) to s.Return s.
- <frequency>
The frequency in hertz serialized as per <number> followed by the literal string "
hz".- <identifier>
The identifier escaped.
- <integer>
A base-ten integer using digits 0-9 (U+0030 to U+0039) in the shortest form possible, preceded by "
-" (U+002D) if it is negative.- <length>
-
A length of zero is represented by the literal string "
0px".Absolute lengths: the number of millimeters serialized as per <number> followed by the literal string "
mm".Rumor has it absolute lengths will become relative lengths. Centimeters would be compatible with <resolution>...
Relative lengths: the <number> component serialized as per <number> followed by the unit in its canonical form as defined in its respective specification.
- <number>
-
A base-ten number using digits 0-9 (U+0030 to U+0039) in the shortest form possible, using "
." to separate decimals (if any), preceded by "-" (U+002D) if it is negative.JavaScript's
ToStringalgorithm cannot be used since it can serialize numbers using an exponent, which would not round-trip in CSS. - <percentage>
The <number> component serialized as per <number> followed by the literal string "
%" (U+0025).- <resolution>
The resolution in dots per centimeter serialized as per <number> followed by the literal string "
dpcm".- <shape>
-
The return value of the following algorithm:
Let s be the string "
rect(".Let list be a list of the CSS component values belonging to <shape>.
Let each item in list be the result of invoking serialize a CSS component value of that item.
Append the result of invoking serialize a comma-separated list on list to s.
Append "
)" (U+0029) to s.Return s.
- <string>
- <family-name>
- <specific-voice>
The string string escaped.
- <time>
The time in seconds serialized as per <number> followed by the literal string "
s".- <uri>
The absolute URL URL escaped.
<absolute-size>, <border-width>, <border-style>, <bottom>, <generic-family>, <generic-voice>, <left>, <margin-width>, <padding-width>, <relative-size>, <right>, and <top>, are considered macros by this specification. They all represent instances of components outlined above.
One idea is that we can remove this section somewhere in the CSS3/CSS4 timeline by moving the above definitions to the drafts that define the CSS components.
6.7.2.1 Examples
Here are some examples of before and after results on specified values. The before column could be what the author wrote in a style sheet, while the after column shows what querying the DOM would return.
| Before | After |
|---|---|
background: none | background: rgba(0, 0, 0, 0)
|
outline: none | outline: invert
|
border: none | border: medium
|
list-style: none | list-style: disc
|
margin: 0 1px 1px 1px | margin: 0px 1px 1px
|
azimuth: behind left | azimuth: 220deg
|
font-family: a, 'b"', serif | font-family: "a", "b\"", serif
|
content: url('h)i') '\[\]' | content: url("h)i") "[]"
|
azimuth: leftwards | azimuth: leftwards
|
color: rgb(18, 52, 86) | color: #123456
|
color: rgba(000001, 0, 0, 1) | color: #000000
|
Some of these need to be updated per the new rules.
7 DOM Access to CSS Declaration Blocks
The ElementCSSInlineStyle interface provides access to inline style properties of an element.
[NoInterfaceObject]
interface ElementCSSInlineStyle {
[SameObject, PutForwards=cssText] readonly attribute CSSStyleDeclaration style;
};
The style attribute must return a live CSS declaration block with the following
properties:
- readonly flag
Unset.
- declarations
The result of parsing the
stylecontent attribute, in specified order. If thestylecontent attribute is absent, the object represents an empty list of CSS declarations. Mutating the declarations must set thestylecontent attribute on the context object to the serialization of the declarations. If thestylecontent attribute is set, changed or removed, the declarations must be updated as appropriate.- parent CSS rule
Null.
- owner node
The context object.
If the user agent supports HTML, the following IDL applies: [HTML]
HTMLElement implements ElementCSSInlineStyle;
If the user agent supports SVG, the following IDL applies: [SVG]
SVGElement implements ElementCSSInlineStyle;
7.2 Extensions to the Window Interface
partial interface Window { [NewObject] CSSStyleDeclaration getComputedStyle(Element elt, optional DOMString pseudoElt); };
The getComputedStyle(elt, pseudoElt) method must run these
steps:
Let doc be the
Documentassociated with theWindowobject on which the method was invoked.Let obj be elt.
If pseudoElt is as an ASCII case-insensitive match for either ':before' or '::before' let obj be the ::before pseudo-element of elt.
If pseudoElt is as an ASCII case-insensitive match for either ':after' or '::after' let obj be the ::after pseudo-element of elt.
-
Return a live CSS declaration block with the following properties:
- readonly flag
Set.
- declarations
All longhand properties that are supported CSS properties, in lexicographical order, with the value being the resolved value computed for obj using the style rules associated with doc.
This means that even if obj is in a different document (e.g. one fetched via
XMLHttpRequest) it will still use the style rules associated with the document that is associated with the global object on whichgetComputedStyle()was invoked to compute the CSS declaration block.- parent CSS rule
Null.
- owner node
obj.
Because of historical IDL limitations the getComputedStyle() method used to be on
a separate interface, ViewCSS.
The getComputedStyle() method exposes information from CSS style
sheets with the origin-clean flag unset.
7.3 The GetStyleUtils Interface
The associated document of an object obj is obj's node
document if obj is an Element object, or obj's associated
Element object's node document if obj is a
PseudoElement object.
[NoInterfaceObject]
interface GetStyleUtils {
[SameObject] readonly attribute CSSStyleDeclaration cascadedStyle;
[SameObject] readonly attribute CSSStyleDeclaration rawComputedStyle;
[SameObject] readonly attribute CSSStyleDeclaration usedStyle;
};
The cascadedStyle attribute must return a live CSS declaration block
with the following properties:
- readonly flag
Set.
- declarations
All longhand properties that are supported CSS properties, in lexicographical order, that have a cascaded value for the context object, with the value being the cascaded value computed for the context object using the style rules associated with the context object's associated document.
- parent CSS rule
Null.
- owner node
The context object.
The rawComputedStyle attribute must return a live CSS declaration
block with the following properties:
- readonly flag
Set.
- declarations
All longhand properties that are supported CSS properties, in lexicographical order, with the value being the computed value computed for the context object using the style rules associated with the context object's associated document.
- parent CSS rule
Null.
- owner node
The context object.
The usedStyle attribute must return a live CSS declaration block with the
following properties:
- readonly flag
Set.
- declarations
All longhand properties that are supported CSS properties, in lexicographical order, with the value being the used value computed for the context object using the style rules associated with the context object's associated document.
- parent CSS rule
Null.
- owner node
The context object.
The cascadedStyle, rawComputedStyle
and usedStyle methods expose information from CSS style sheets with the
origin-clean flag unset.
7.4 Extensions to the Element Interface
partial interface Element { PseudoElement? pseudo(DOMString pseudoElt); }; Element implements GetStyleUtils;
The pseudo(pseudoElt) method, when invoked, must run the following steps:
If pseudoElt is as an ASCII case-insensitive match for either ':before' or '::before' return the
PseudoElementrepresenting the ::before pseudo-element of the context object.If pseudoElt is as an ASCII case-insensitive match for either ':after' or '::after' return the
PseudoElementrepresenting the ::after pseudo-element of the context object.Return null.
When invoked with an argument that returns a PseudoElement object representing a particular pseudo-element, the same object must be
returned as returned by an earlier call that represent the same pseudo-element.
7.5 The PseudoElement Interface
The PseudoElement interface is used for representing CSS pseudo-elements. A PseudoElement object is associated with an
Element object.
interface PseudoElement {
};
PseudoElement implements GetStyleUtils;
8 Utility APIs
8.1 The CSS.escape() Method
The CSS interface is defined in CSS Conditional Rules Module. [CSSCONDITIONAL]
partial interface CSS {
static DOMString escape(DOMString ident);
};
The escape(ident) method must return the result of invoking serialize an identifier of
ident. Any exceptions thrown must be re-thrown.
For example, to escape a string for use as part of a selector, the escape() method can be used:
var element = document.querySelector('#' + CSS.escape(id) + ' > img');
The escape() method can also be used for escaping strings, although it escapes characters that don't strictly need to be
escaped:
var element = document.querySelector('a[href="#' + CSS.escape(fragment) + '"]');
9 Resolved Values
getComputedStyle() was
historically defined to return the "computed value" of an element or
pseudo-element. However, the concept of "computed value" changed between
revisions of CSS while the implementation of
getComputedStyle() had to
remain the same for compatibility with deployed scripts. To address this
issue this specification introduces the concept of a
resolved value.
The resolved value for a given property can be determined as follows:
- 'line-height'
The resolved value is the used value.
- 'height'
- 'margin'
- 'margin-bottom'
- 'margin-left'
- 'margin-right'
- 'margin-top'
- 'padding'
- 'padding-bottom'
- 'padding-left'
- 'padding-right'
- 'padding-top'
- 'width'
If the property applies to the element or pseudo-element and the resolved value of the 'display' property is not 'none', the resolved value is the used value. Otherwise the resolved value is the computed value.
- 'bottom'
- 'left'
- 'right'
- 'top'
If the property applies to a positioned element and the resolved value of the 'display' property is not 'none', the resolved value is the used value. Otherwise the resolved value is the computed value.
- Any other property
The resolved value is the computed value.
10 IANA Considerations
10.1 Default-Style
This section describes a header field for registration in the Permanent Message Header Field Registry.
- Header field name
- Default-Style
- Applicable protocol
- http
- Status
- standard
- Author/Change controller
- W3C
- Specification document(s)
- This document is the relevant specification.
- Related information
- None.
References
- [CSS]
- CSS, Bert Bos, Tantek Çelik, Ian Hickson et al.. W3C.
- [CSSCASCADE]
- CSS Cascading and Inheritance, Håkon Wium Lie, fantasai and Tab Atkins Jr..
- [CSSCONDITIONAL]
- CSS Conditional Rules Module, L. David Baron.
- [CSSNAMESPACES]
- CSS Namespaces Module, Elika J. Etemad and Anne van Kesteren. W3C.
- [CSSPAGE]
- CSS Paged Media Module, Melinda Grant, Håkon Wium Lie, Elika J. Etemad et al.. W3C.
- [CSSSYNTAX]
- CSS Syntax Module, Tab Atkins Jr.. W3C.
- [CSSVARIABLES]
- CSS Custom Properties for Cascading Variables Module, Tab Atkins Jr.. W3C.
- [DOM]
- DOM, Anne van Kesteren, Aryeh Gregor and Ms2ger. WHATWG.
- [DOM2STYLE]
- (Non-normative) Document Object Model (DOM) Level 2 Style Specification, Chris Wilson, Philippe Le Hégaret and Vidur Apparao. W3C.
- [FETCH]
- Fetch, Anne van Kesteren. WHATWG.
- [HTML]
- HTML, Ian Hickson. WHATWG.
- [RFC2119]
- Key words for use in RFCs to Indicate Requirement Levels, Scott Bradner. IETF.
- [SELECTORS]
- Selectors, Elika J. Etemad and Tab Atkins Jr.. W3C.
- [SVG]
- (Non-normative) Scalable Vector Graphics (SVG), O. Andersson, R. Berjon, E. Dahlström et al.. W3C.
- [URL]
- URL, Anne van Kesteren. WHATWG.
- [XML]
- Extensible Markup Language, Tim Bray, Jean Paoli, C. M. Sperberg-McQueen et al.. W3C.
- [XMLSS]
- Associating Style Sheets with XML documents 1.0 (Second Edition), James Clark, Simon Pieters and Henry S. Thompson. W3C.
Acknowledgments
The editors would like to thank Alexey Feldgendler, Björn Höhrmann, Boris Zbasky, Brian Kardell, Christian Krebs, Daniel Glazman, David Baron, fantasai, Hallvord R. M. Steen, Ian Hickson, John Daggett, Lachlan Hunt, Mike Sherov, Morten Stenshorne, Ms2ger, Øyvind Stenhaug, Peter Sloetjes, Philip Taylor, Robert O'Callahan, Simon Sapin, Sjoerd Visscher, Sylvain Galineau, Tarquin Wilton-Jones, and Zack Weinberg for contributing to this specification.
Additional thanks to Ian Hickson for writing the initial version of the alternative style sheets API and canonicalization (now serialization) rules for CSS values.