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[DOM].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.Terminology
This specification employs certain terminology from the following documents:DOM,HTML,CSS Syntax,Encoding,URL,Fetch,Associating Style Sheets with XML documentsandXML.[DOM][HTML][CSS3SYN][ENCODING][URL][FETCH][XML-STYLESHEET][XML]
When this specification talks about objectA
whereA
is actually an interface, it generally means an object implementing interfaceA
.
The termssetandunsetto 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 termsupported styling languagerefers to CSS.
Note:If another styling language becomes supported in user agents, this specification is expected to be updated as necessary.
The termsupported CSS propertyrefers to a CSS property that the user agent implements, including any vendor-prefixed properties, but excludingcustom properties.Asupported CSS propertymust be in its lowercase form for the purpose of comparisons in this specification.
In this specification the::beforeand::afterpseudo-elements are assumed to exist for all elements even if no box is generated for them.
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 acase-sensitivemanner.
2.1.Common Serializing Idioms
Toescape a charactermeans to create a string of
"\
"(U+005C), followed by the character.
Toescape a character as code pointmeans 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).
Toserialize an identifiermeans to create a string represented by the concatenation of, for each character of the identifier:
- If the character is NULL (U+0000), then the REPLACEMENT CHARACTER (U+FFFD).
- If the character is in the range [\1-\1f] (U+0001 to U+001F) or is U+007F, then the characterescaped as code point.
- If the character is the first character and is in the range [0-9] (U+0030 to U+0039), then the characterescaped 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 characterescaped as code point. - If the character is the first character and is a "
-
"(U+002D), and there is no second character, then theescapedcharacter. - 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, theescapedcharacter.
Toserialize a stringmeans 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 the REPLACEMENT CHARACTER (U+FFFD).
- If the character is in the range [\1-\1f] (U+0001 to U+001F) or is U+007F, the characterescaped as code point.
- If the character is ' "' (U+0022) or"
\
" (U+005C), theescapedcharacter. - Otherwise, the character itself.
Note:"'
"(U+0027) is not escaped because strings
are always serialized with '" ' (U+0022).
Toserialize a URLmeans to create a string represented by
"url(
",followed by theserializationof the URL as a
string, followed by ")
".
Toserialize a LOCALmeans to create a string represented by
"local(
",followed by theserializationof the LOCAL as a
string, followed by ")
".
Toserialize a comma-separated listconcatenate all items of
the list in list order while separating them by ",
",i.e.,
COMMA (U+002C) followed by a single SPACE (U+0020).
Toserialize a whitespace-separated listconcatenate all
items of the list in list order while separating them by "",i.e.,
a single SPACE (U+0020).
Note: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.
3.CSSOMString
Most strings in CSSOM interfaces use theCSSOMString
type.
Each implementation chooses to define it as eitherUSVString
orDOMString
:
typedef USVString CSSOMString ;
Or, alternatively:
typedef DOMString CSSOMString ;
DOMString
would preserve them,
whereasUSVString
would replace them with U+FFFD REPLACEMENT CHARACTER.
This choice effectively allows implementations to do this replacement, but does not require it.
UsingUSVString
enables an implementation
to use UTF-8 internally to represent strings in memory.
Since well-formed UTF-8 specifically disallowssurrogatecode points,
it effectively requires this replacement.
On the other hand, implementations that internally represent strings as 16-bitcode unitsmight prefer to avoid the cost of doing this replacement.
4.Media Queries
Media queriesare defined by[MEDIAQUERIES].This section defines various concepts aroundmedia queries,including their API and serialization form.
4.1.Parsing Media Queries
Toparse a media query listfor a given stringsinto amedia query listis defined in the Media Queries specification. Return the list of media queries that the algorithm defined there gives.
Note:A media query that ends up being "ignored" will turn
into "not all
".
Toparse a media queryfor a given stringsmeans to follow theparse a media query liststeps and return null if more than one media query is returned or a media query if a single media query is returned.
Note:Again, a media query that ends up being "ignored" will
turn into "not all
".
4.2.Serializing Media Queries
Toserialize a media query listrun these steps:
- If themedia query listis empty, then return the empty string.
- Serializeeach media query in the list of media queries, in the same order as they appear in themedia query list,and thenserializethe list.
Toserialize a media queryletsbe the empty string, run the steps below:
- If themedia queryis negated append "
not
",followed by a single SPACE (U+0020), tos. - Lettypebe theserialization as an identifierof themedia typeof themedia query,converted to ASCII lowercase.
- If themedia querydoes not containmedia featuresappendtype,tos, then returns.
- Iftypeis not "
all
"or if the media query is negated appendtype,followed by a single SPACE (U+0020), followed by "and
",followed by a single SPACE (U+0020), tos. -
Then, for eachmedia feature:
- Append a "
(
"(U+0028), followed by themedia featurename,converted to ASCII lowercase, tos. - If a value is given append a "
:
"(U+003A), followed by a single SPACE (U+0020), followed by theserialized media feature value, tos. - Append a "
)
"(U+0029) tos. - If this is not the lastmedia featureappend a single SPACE (U+0020),
followed by "
and
",followed by a single SPACE (U+0020), tos.
- Append a "
- Returns.
Input | Output |
---|---|
not screen and (min-WIDTH:5px) AND (max-width:40px) |
not screen and (min-width: 5px) and (max-width: 40px) |
all and (color) and (color) |
(color) and (color) |
4.2.1.Serializing Media Feature Values
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.
Toserialize a media feature valuenamedvlocatevin 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 isportrait:"portrait ".
If the value islandscape:"landscape ".
|
aspect-ratio | ... |
device-aspect-ratio | ... |
color | ... |
color-index | ... |
monochrome | ... |
resolution | ... |
scan | If the value isprogressive:"progressive ".
If the value isinterlace:"interlace ".
|
grid | ... |
Other specifications can extend this table and vendor-prefixed media features can have custom serialization formats as well.
4.3.Comparing Media Queries
Tocompare media queriesm1andm2means toserializethem both and return true if they are acase-sensitivematch and false if they are not.
4.4.TheMediaList
Interface
An object that implements theMediaList
interface has an associatedcollection of media queries.
[Exposed =Window ]interface {
MediaList stringifier attribute [LegacyNullToEmptyString ]CSSOMString mediaText ;readonly attribute unsigned long length ;getter CSSOMString ?item (unsigned long );
index undefined appendMedium (CSSOMString );
medium undefined deleteMedium (CSSOMString ); };
medium
The object’ssupported property indicesare the numbers in the range zero to one less than the number of media queries in thecollection of media queriesrepresented by the collection. If there are no such media queries, then there are nosupported property indices.
Tocreate aMediaList
objectwith a stringtext,run the following steps:
- Create a new
MediaList
object. - Set its
mediaText
attribute totext. - Return the newly created
MediaList
object.
ThemediaText
attribute, on getting, must return aserializationof thecollection of media queries.
Setting themediaText
attribute must run these steps:
- Empty thecollection of media queries.
- If the given value is the empty string, then return.
- Append all the media queries as a result ofparsingthe given value to thecollection of media queries.
Theitem(index)
method must return aserializationof the media query in thecollection of media queriesgiven byindex,or null, ifindexis greater than or equal to the number of media queries
in thecollection of media queries.
Thelength
attribute must return the number of media queries in thecollection of media
queries.
TheappendMedium(medium)
method must run these steps:
- Letmbe the result ofparsingthe given value.
- Ifmis null, then return.
- Ifcomparingmwith any of the media queries in thecollection of media queriesreturns true, then return.
- Appendmto thecollection of media queries.
ThedeleteMedium(medium)
method must run these steps:
- Letmbe the result ofparsingthe given value.
- Ifmis null, then return.
- Remove any media query from thecollection of media queriesfor whichcomparingthe media query withmreturns true.
If nothing was removed, thenthrowa
NotFoundError
exception.
5.Selectors
Selectors are defined in the Selectors specification. This section mainly defines how to serialize them.
5.1.Parsing Selectors
Toparse a group of selectorsmeans to parse the value using theselectors_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
Toserialize a group of selectorsserializeeach selector in the group of selectors and thenserializea comma-separated list of these serializations.
Toserialize a selectorletsbe the empty string, run the steps below for each part of the chain of the selector, and finally returns:
- If there is only onesimple selectorin thecompound selectorswhich is auniversal selector,append the result ofserializingtheuniversal selectortos.
- Otherwise, for eachsimple selectorin thecompound selectorsthat is not a universal selector of which thenamespace prefixmaps to a namespace that is not thedefault namespaceserializethesimple selectorand append the result tos.
- If this is not the last part of the chain of the selector append a
single SPACE (U+0020), followed by the combinator
"
>
", "+
", "~
", ">>
", "||
", as appropriate, followed by another single SPACE (U+0020) if the combinator was not whitespace, tos. - 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, tos.
Toserialize a simple selectorletsbe the empty string, run the steps below, and finally returns:
- type selector
- universal selector
-
- If thenamespace prefixmaps to a namespace that is
not thedefault namespaceand is not the
null namespace (not in a namespace) append theserializationof thenamespace prefixas an identifier, followed by a
"
|
"(U+007C) tos. - If thenamespace prefixmaps to a namespace that is
the null namespace (not in a namespace) append
"
|
"(U+007C) tos. - If this is a type selector append theserializationof the element name as an identifier tos.
- If this is a universal selector append "
*
"(U+002A) tos.
- If thenamespace prefixmaps to a namespace that is
not thedefault namespaceand is not the
null namespace (not in a namespace) append theserializationof thenamespace prefixas an identifier, followed by a
"
- attribute selector
-
- Append "
[
"(U+005B) tos. - If thenamespace prefixmaps to a namespace that is
not the null namespace (not in a namespace) append theserializationof thenamespace prefixas an identifier, followed by a
"
|
"(U+007C) tos. - Append theserializationof the attribute name as an identifier tos.
- If there is an attribute value specified, append
"
=
", "~=
", "|=
", "^=
", "$=
",or "*=
" as appropriate (depending on the type of attribute selector), followed by theserializationof the attribute value as a string, tos. - If the attribute selector has the case-sensitivity flag present,
append "
i
"(U+0020 U+0069) tos. - Append "
]
"(U+005D) tos.
- Append "
- class selector
- Append a "
.
"(U+002E), followed by theserializationof the class name as an identifier tos. - ID selector
- Append a "
#
"(U+0023), followed by theserializationof the ID as an identifier tos. - pseudo-class
-
If the pseudo-class does not accept arguments append
"
:
"(U+003A), followed by the name of the pseudo-class, tos.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(s) determined as per below, followed by ")
"(U+0029), tos.:lang()
- Theserialization of a comma-separated listof each argument’sserialization as a string,preserving relative order.
:nth-child()
:nth-last-child()
:nth-of-type()
:nth-last-of-type()
- The result of serializing the value using the rules toserialize an <an+b> value.
:not()
- The result of serializing the value using the rules forserializing a group of selectors.
6.CSS
6.1.CSS Style Sheets
ACSS style sheetis an abstract concept that
represents a style sheet as defined by the CSS specification. In the CSSOM aCSS style sheetis represented as aCSSStyleSheet
object.
CSSStyleSheet(options)
- When called, execute the steps tocreate a constructed CSSStyleSheetgivenoptionsand return the result.
- Tocreate a constructed
CSSStyleSheet
givenCSSStyleSheetInit
options,run these steps: -
- Construct a new
CSSStyleSheet
objectsheet. - Setsheet’slocationto thebase URLof theassociated Documentfor thecurrent global object.
- Setsheet’sstylesheet base URLto the
baseURL
attribute value fromoptions. - Setsheet’sparent CSS style sheetto null.
- Setsheet’sowner nodeto null.
- Setsheet’sowner CSS ruleto null.
- Setsheet’stitleto the the empty string.
- Unsetsheet’salternate flag.
- Setsheet’sorigin-clean flag.
- Setsheet’sconstructed flag.
- Setsheet’sConstructor documentto theassociated Documentfor thecurrent global object.
- If the
media
attribute ofoptionsis a string,create a MediaList objectfrom the string and assign it assheet’smedia. Otherwise,serialize a media query listfrom the attribute and thencreate a MediaList objectfrom the resulting string and set it assheet’smedia. - If the
disabled
attribute ofoptionsis true, setsheet’sdisabled flag. - Returnsheet.
- Construct a new
ACSS style sheethas a number of associated state items:
- type
- The literal string "
text/css
". - location
- Specified when created. Theabsolute-URL stringof the first request of theCSS style sheetor null if theCSS style sheetwas embedded. Does not change during the lifetime of theCSS style sheet.
- parent CSS style sheet
- Specified when created. TheCSS style sheetthat is the parent of theCSS style sheetor null if there is no associated parent.
- owner node
- Specified when created. The DOM node associated with theCSS style sheetor null if there is no associated DOM node.
- owner CSS rule
- Specified when created. TheCSS rulein theparent CSS style sheetthat caused the inclusion of theCSS style sheetor null if there is no associated rule.
- media
-
Specified when created. The
MediaList
object associated with theCSS style sheet.If this property is specified to a string, themediamust be set to the return value of invokingcreate a
MediaList
objectsteps for that string.If this property is specified to an attribute of theowner node,themediamust be set to the return value of invokingcreate a
MediaList
objectsteps for the value of that attribute. Whenever the attribute is set, changed or removed, themedia’smediaText
attribute must be set to the new value of the attribute, or to null if the attribute is absent.Note:Changing themedia’s
mediaText
attribute does not change the corresponding attribute on theowner node.Note:Theowner nodeof aCSS style sheet,if non-null, is the node whoseassociated CSS style sheetis theCSS style sheetin question, when theCSS style sheetisadded.
- title
-
Specified when created. The title of theCSS style sheet,which can be the empty string.
In the following, thetitleis 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 theowner node,thetitlemust be set to the value of that attribute. Whenever the attribute is set, changed or removed, thetitlemust be set to the new value of the attribute, or to the empty string if the attribute is absent.
Note:HTML onlyspecifiestitleto be an attribute of theowner nodeif the node is inin a document tree.
- alternate flag
-
Specified when created. Either set or unset. Unset by default.
The followingCSS style sheetshave theiralternate flagset:
<?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.
Note:Even when unset it does not necessarily mean that theCSS style sheetis actually used for rendering.
- CSS rules
- The CSS rules associated with theCSS style sheet.
- origin-clean flag
- Specified when created. Either set or unset. If it is set, the API allows reading and modifying of theCSS rules.
- constructed flag
- Specified when created. Either set or unset. Unset by default. Signifies whether this stylesheet was created by invoking the IDL-defined constructor.
- disallow modification flag
- Either set or unset. Unset by default. If set, modification of the stylesheet’s rules is not allowed.
- constructor document
- Specified when created. The
Document
a constructed stylesheet is associated with. Null by default. Only non-null for stylesheets that haveconstructed flagset. - stylesheet base URL
- The base URL to use when resolving relative URLs in the stylesheet. Null by default. Only non-null for stylesheets that haveconstructed flagset.
6.1.1.TheStyleSheet
Interface
TheStyleSheet
interface represents an abstract, base style sheet.
[Exposed =Window ]interface {
StyleSheet readonly attribute CSSOMString type ;readonly attribute USVString ?href ;readonly attribute (Element or ProcessingInstruction )?ownerNode ;readonly attribute CSSStyleSheet ?parentStyleSheet ;readonly attribute DOMString ?title ; [SameObject ,PutForwards =mediaText ]readonly attribute MediaList media ;attribute boolean disabled ; };
Thetype
attribute must return thetype.
Thehref
attribute must return thelocation.
TheownerNode
attribute must return theowner node.
TheparentStyleSheet
attribute must return theparent CSS style sheet.
Thetitle
attribute must return thetitleor null iftitleis the empty string.
Themedia
attribute must return themedia.
Thedisabled
attribute, on getting, must return true if thedisabled flagis set, or false otherwise. On setting, thedisabled
attribute must set thedisabled flagif the new value is true, or unset thedisabled flagotherwise.
6.1.2.TheCSSStyleSheet
Interface
TheCSSStyleSheet
interface represents aCSS style sheet.
[Exposed =Window ]interface :
CSSStyleSheet StyleSheet {constructor (optional CSSStyleSheetInit = {});
options readonly attribute CSSRule ?ownerRule ; [SameObject ]readonly attribute CSSRuleList cssRules ;unsigned long insertRule (CSSOMString ,
rule optional unsigned long = 0);
index undefined deleteRule (unsigned long );
index Promise <CSSStyleSheet >replace (USVString );
text undefined replaceSync (USVString ); };
text dictionary {
CSSStyleSheetInit DOMString =
baseURL null ; (MediaList or DOMString )= "";
media boolean =
disabled false ; };
TheownerRule
attribute must return theowner CSS rule.
If a value other than null is ever returned, then that same value must always be returned on each get access.
ThecssRules
attribute must follow these steps:
- If theorigin-clean flagis unset,throwa
SecurityError
exception. -
Return a read-only, live
CSSRuleList
object representing theCSS rules.Note:Even though the returned
CSSRuleList
object 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.
TheinsertRule(rule,index)
method must run the following steps:
- If theorigin-clean flagis unset,throwa
SecurityError
exception. - If thedisallow modification flagis set, throw a
NotAllowedError
DOMException
. - Letparsed rulebe the return value of invokingparse a rulewithrule.
- Ifparsed ruleis a syntax error, returnparsed rule.
- Ifparsed ruleis an@importrule, and theconstructed flagis set, throw
a
SyntaxError
DOMException
. - Return the result of invokinginsert a CSS rulerulein theCSS rulesatindex.
ThedeleteRule(index)
method must run the following steps:
- If theorigin-clean flagis unset,throwa
SecurityError
exception. - If thedisallow modification flagis set, throw a
NotAllowedError
DOMException
. - Remove a CSS rulein theCSS rulesatindex.
Thereplace(text)
method must run the following steps:
- Letpromisebe a promise.
- If theconstructed flagis not set, or thedisallow modification flagis set, rejectpromisewith a
NotAllowedError
DOMException
and returnpromise. - Set thedisallow modification flag.
-
In parallel,do these steps:
- Letrulesbe the result of runningparse a list of rulesfromtext.Ifrulesis not a list of rules (i.e. an error occurred during parsing), setrulesto an empty list.
- Ifrulescontains one or more@importrules,remove those rulesfromrules.
- Setsheet’sCSS rulestorules.
- Unsetsheet’sdisallow modification flag.
- Resolvepromisewithsheet.
- Returnpromise.
ThereplaceSync(text)
method must run the
steps tosynchronously replace the rules of a CSSStyleSheeton thisCSSStyleSheet
giventext.
Tosynchronously replace the rules of a CSSStyleSheetonsheetgiventext,run these steps:
- If theconstructed flagis not set, or thedisallow modification flagis set, throw a
NotAllowedError
DOMException
. - Letrulesbe the result of runningparse a list of rulesfromtext.Ifrulesis not a list of rules (i.e. an error occurred during parsing), setrulesto an empty list.
- Ifrulescontains one or more@importrules,remove those rulesfromrules.
- Setsheet’sCSS rulestorules.
6.1.2.1.Deprecated CSSStyleSheet members
Note:These members are required for compatibility with existing sites.
partial interface CSSStyleSheet { [SameObject ]readonly attribute CSSRuleList rules ;long addRule (optional DOMString = "undefined",
selector optional DOMString = "undefined",
style optional unsigned long );
index undefined removeRule (optional unsigned long = 0); };
index
Therules
attribute must follow the same steps ascssRules
,and return the same objectcssRules
would return.
TheremoveRule(index)
method must run the same steps asdeleteRule()
.
TheaddRule(selector,block,optionalIndex)
method must run the following steps:
- Letrulebe an empty string.
- Appendselectortorule.
- Append
"{"
torule. - Ifblockis not empty, appendblock,followed by a space, torule.
- Append
"}"
torule - LetindexbeoptionalIndexif provided, or the number ofCSS rulesin the stylesheet otherwise.
- Call
insertRule()
,withruleandindexas arguments. - Return
-1
.
Authors should not use these members
and should instead use and teach the standardCSSStyleSheet
interface defined earlier,
which is consistent withCSSGroupingRule
.
6.2.CSS Style Sheet Collections
Below various new concepts are defined that are associated with eachDocumentOrShadowRoot
object.
EachDocumentOrShadowRoot
has an associated list of zero or moreCSS style sheets,named thedocument or shadow root CSS style sheets.This is
an ordered list that contains:
- AnyCSS style sheetscreated from HTTP
Link
headers, in header order - AnyCSS style sheetsassociated with the
DocumentOrShadowRoot
,intree order
EachDocumentOrShadowRoot
has an associated list of zero or moreCSS style sheets,named thefinal CSS style sheets.This is
an ordered list that contains:
- Thedocument or shadow root CSS style sheets.
- The contents of
DocumentOrShadowRoot
'sadoptedStyleSheets
'backing list,in array order.
Tocreate a CSS style sheet,run these steps:
- Create a newCSS style sheetobject and set its properties as specified.
-
Then run theadd a CSS style sheetsteps for the newly createdCSS style sheet.
If theorigin-clean flagis unset, this can expose information from the user’s intranet.
Toadd a CSS style sheet,run these steps:
- Add theCSS style sheetto the list ofdocument or shadow root CSS style sheetsat the appropriate location. The remainder of these steps deal with thedisabled flag.
- If thedisabled flagis set, then return.
- If thetitleis not the empty string, thealternate flagis unset, andpreferred CSS style sheet set nameis the empty stringchange the preferred CSS style sheet set nameto thetitle.
-
If any of the following is true, then unset thedisabled flagand return:
- Thetitleis the empty string.
- Thelast CSS style sheet set nameis null and thetitleis acase-sensitivematch for thepreferred CSS style sheet set name.
- Thetitleis acase-sensitivematch for thelast CSS style sheet set name.
- Set thedisabled flag.
Toremove a CSS style sheet,run these steps:
- Remove theCSS style sheetfrom the list ofdocument or shadow root CSS style sheets.
- Set theCSS style sheet’sparent CSS style sheet,owner nodeandowner CSS ruleto null.
Apersistent CSS style sheetis aCSS style sheetfrom thedocument or shadow root CSS style sheetswhosetitleis the empty string and whosealternate flagis unset.
ACSS style sheet setis an ordered collection of one or moreCSS style sheetsfrom thedocument or shadow root CSS style sheetswhich have an identicaltitlethat is not the empty string.
ACSS style sheet set nameis thetitletheCSS style sheet sethas in common.
Anenabled CSS style sheet setis aCSS style sheet setof which eachCSS style sheethas itsdisabled flagunset.
Toenable a CSS style sheet setwith namename,run these steps:
- Ifnameis the empty string, set thedisabled flagfor eachCSS style sheetthat is in aCSS style sheet setand return.
- Unset thedisabled flagfor eachCSS style sheetin aCSS style sheet setwhoseCSS style sheet set nameis acase-sensitivematch fornameand set it for all otherCSS style sheetsin aCSS style sheet set.
Toselect a CSS style sheet setwith namename,run these steps:
- enable a CSS style sheet setwith namename.
- Setlast CSS style sheet set nametoname.
Alast CSS style sheet set nameis a concept to determine whatCSS style sheet setwas lastselected.Initially its value is null.
Apreferred CSS style sheet set nameis a concept to determine whichCSS style sheetsneed to have theirdisabled flagunset. Initially its value is the empty string.
Tochange the preferred CSS style sheet set namewith namename,run these steps:
- Letcurrentbe thepreferred CSS style sheet set name.
- Setpreferred CSS style sheet set nametoname.
- Ifnameis not acase-sensitivematch forcurrentandlast CSS style sheet set nameis nullenable a CSS style sheet setwith namename.
6.2.1.The HTTP Default-Style Header
The HTTPDefault-Styleheader can be used to set thepreferred CSS style sheet set nameinfluencing whichCSS style sheet setis (initially) theenabled CSS style sheet set.
For each HTTPDefault-Styleheader, in header order, the user agent mustchange the preferred CSS style sheet set namewith name being the value of the header.
6.2.2.TheStyleSheetList
Interface
TheStyleSheetList
interface represents an ordered collection ofCSS style sheets.
[Exposed =Window ]interface {
StyleSheetList getter CSSStyleSheet ?item (unsigned long );
index readonly attribute unsigned long length ; };
The object’ssupported property indicesare the numbers in the range zero to one less than the number ofCSS style sheetsrepresented by the collection. If there are no suchCSS style sheets, then there are nosupported property indices.
Theitem(index)
method must return theindexthCSS style
sheetin the collection. If there is noindexth object in the collection, then the method must return null.
Thelength
attribute must return the number ofCSS style sheetsrepresented by the collection.
6.2.3.Extensions to theDocumentOrShadowRoot
Interface Mixin
partial interface mixin DocumentOrShadowRoot { [SameObject ]readonly attribute StyleSheetList styleSheets ;attribute ObservableArray <CSSStyleSheet >adoptedStyleSheets ; };
ThestyleSheets
attribute must return aStyleSheetList
collection representing
thedocument or shadow root CSS style sheets.
Theset an indexed valuealgorithm foradoptedStyleSheets
,givenvalueandindex,
is the following:
- Ifvalue’sconstructed flagis not set, or itsconstructor documentis not equal to this
DocumentOrShadowRoot
'snode document,throw a "NotAllowedError
"DOMException
.
6.3.Style Sheet Association
This section defines the interface anowner nodeof aCSS style sheethas to
implement and defines the requirements forxml-stylesheet processing instructionsand HTTPLink
headers when the link
relation type is anASCII case-insensitivematch for
"stylesheet
".
6.3.1.Fetching CSS style sheets
Tofetch a CSS style sheetwith parsed URLparsed URL,referrerreferrer,documentdocument,optionally a set of parametersparameters(used as input to creating arequest), follow these steps:
- Letoriginbedocument’sorigin.
- Letrequestbe a newrequest,with theurlparsed URL,originorigin,referrerreferrer,and if specified the set of parametersparameters.
- Letresponsebe the result offetchingrequest.
- Wait untilresponseis available.
- Ifresponseis anetwork error,return an error.
- Ifdocumentis inquirks mode,responseisCORS-same-originand theContent-Type metadataofresponseis not asupported styling languagechange theContent-Type metadataofresponseto
text/css
. - Ifresponseis not in asupported styling languagereturn an error.
- Returnresponse.
6.3.2.TheLinkStyle
Interface
Theassociated CSS style sheetof a node is theCSS style sheetin the list ofdocument or shadow root CSS style sheetsof which theowner nodeis said node.
This node must also implement theLinkStyle
interface.
interface mixin {
LinkStyle readonly attribute CSSStyleSheet ?sheet ; };
Thesheet
attribute must return theassociated CSS style sheetfor the node or null
if there is noassociated CSS style sheet.
style
element has asheet
attribute that returns aStyleSheet
object representing the style sheet, but for
the secondstyle
element, thesheet
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>
Note: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 theLinkStyle
interface. When doing so, they
must also define when aCSS style sheetiscreated.
6.3.4.Requirements on user agents Implementing the xml-stylesheet processing instruction
ProcessingInstruction includes LinkStyle ;
Theprologrefers tonodesthat are children of thedocumentand are notfollowingtheElement
child of thedocument,if any.
When aProcessingInstruction
nodenodebecomes part of theprolog,is no longer part of theprolog,or has itsdatachanged, these steps
must be run:
- If an instance of this algorithm is currently running fornode,abort that instance, and stop the associatedfetchingif applicable.
- Ifnodehas anassociated CSS style sheet,removeit.
- Ifnodeis not anxml-stylesheet processing instruction,then return.
- Ifnodedoes not have an
href
pseudo-attribute,then return. - Lettitlebe the value of the
title
pseudo-attributeor the empty string if thetitle
pseudo-attributeis not specified. - If there is an
alternate
pseudo-attributewhose value is acase-sensitivematch for "yes
"andtitleis the empty string, then return. - If there is a
type
pseudo-attributewhose value is not asupported styling languagethe user agent may return. - Letinput URLbe the value specified by the
href
pseudo-attribute. - Letdocumentbenode’snode document
- Letbase URLbedocument’sdocument base URL.
- Letreferrerbedocument’saddress.
- Letparsed URLbe the return value of invoking theURL parserwith the stringinput URLand the base URLbase URL.
- Ifparsed URLis failure, then return.
- Letresponsebe the result offetching a CSS style sheetwith parsed URLparsed URL, referrerreferrerand documentdocument.
- Ifresponseis an error, then return.
-
Create a CSS style sheetwith the following properties:
- location
- The result of invoking theURL serializerwithparsed URL.
- parent CSS style sheet
- null.
- owner node
- node.
- owner CSS rule
- null.
- media
- The value of the
media
pseudo-attributeif any, or the empty string otherwise. - title
- title.
- alternate flag
- Set if the
alternate
pseudo-attributevalue is acase-sensitivematch for "yes
",or unset otherwise. - origin-clean flag
- Set ifresponseisCORS-same-origin,or unset otherwise.
The CSSenvironment encodingis the result of running the following steps:
- If the element has a
charset
pseudo-attribute,get an encodingfrom that pseudo-attribute’s value. If that succeeds, return the resulting encoding and abort these steps. - Otherwise, return thedocument’s character encoding.[DOM]
A style sheet referenced by anxml-stylesheet processing instructionusing the rules in this section, in the context of
theDocument
of anXML parseris said to bea style sheet that is blocking scriptsif theProcessingInstruction
nodewas created by thatDocument
's parser, and the style sheet was
enabled when the node was created by the parser, the last time theevent loopreached step 1, the node was in that Document,
and the user agent hasn’t given up on loading that particular style sheet
yet. A user agent may give up on such a style sheet at any time.
6.3.5.Requirements on user agents Implementing the HTTP Link Header
For each HTTPLink
header of which one
of the link relation types is anASCII case-insensitivematch
for "stylesheet
"these steps
must be run:
- Lettitlebe the value of the first of all the
title
parameters. If there are no such parameters it is the empty string. - If one of the (other) link relation types is anASCII case-insensitivematch for
"
alternate
"andtitleis the empty string, then return. - Letinput URLbe the value specified.
- Letbase URLbe the document’sdocument base URL.
- Letreferrerbe the document’saddress.
- Letoriginbe the document’sorigin.
- Letparsed URLbe the return value of invoking theURL parserwith the stringinput URLand the base URLbase URL.
- Ifparsed URLis failure, then return.
-
Letresponsebe the result offetching a CSS style sheetwith parsed URLparsed URL,
referrerreferrerand document being the document.
What if the HTML parser hasn’t decided on quirks/non-quirks yet?
-
Create a CSS style sheetwith the following properties:
- location
- The result of invoking theURL serializerwithparsed URL.
- owner node
- null.
- parent CSS style sheet
- null.
- owner CSS rule
- null.
- media
- The value of the first
media
parameter. - title
- title.
- alternate flag
- Set if one of the specified link relation type for this HTTP
Link
header is anASCII case-insensitivematch for "alternate
",or false otherwise. - origin-clean flag
- Set ifresponseisCORS-same-origin,or unset otherwise.
A style sheet referenced by a HTTPLink
header using the rules in this section is said to bea style sheet
that is blocking scriptsif the style sheet was enabled when created,
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
ACSS ruleis an abstract concept that
denotes a rule as defined by the CSS specification. ACSS ruleis represented as an object that implements a subclass of
theCSSRule
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 enclosingCSS ruleor 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 parentCSS style sheetor 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 childCSS rules.The list can be mutated.
In addition to the above state, eachCSS rulemay be associated with other state in accordance with itstype.
Toparse a CSS rulefrom a stringstring,run the following steps:
- Letrulebe the return value of invokingparse a rulewithstring.
- Ifruleis a syntax error, returnrule.
- Letparsed rulebe the result of parsingruleaccording to the appropriate CSS specifications, dropping parts that are said to be ignored. If the whole style rule is dropped, return a syntax error.
- Returnparsed rule.
Toserialize a CSS rule,perform one of the following in accordance with theCSS rule’stype:
CSSStyleRule
-
Return the result of the following steps:
- Letsinitially be
the result of performingserialize a group of selectorson the rule’s associated selectors,
followed by the string "
{
",i.e., a single SPACE (U+0020), followed by LEFT CURLY BRACKET (U+007B). - Letdeclsbe the result of performingserialize a CSS declaration blockon the rule’s associated declarations, or null if there are no such declarations.
- Letrulesbe the result of performingserialize a CSS ruleon each rule in the rule’s
cssRules
list, or null if there are no such rules. - Ifdeclsandrulesare both null, append "}" tos(i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)) and returns.
-
Ifrulesis null:
- Append a single SPACE (U+0020) tos
- Appenddeclstos
- Append "}" tos(i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)).
- Returns.
-
Otherwise:
- Ifdeclsis not null, prepend it torules.
-
For eachruleinrules:
- Append a newline followed by two spaces tos.
- Appendruletos.
- Append a newline followed by RIGHT CURLY BRACKET (U+007D) tos.
- Returns.
- Letsinitially be
the result of performingserialize a group of selectorson the rule’s associated selectors,
followed by the string "
CSSImportRule
-
The result of concatenating the following:
- The string "
@import
"followed by a single SPACE (U+0020). - The result of performingserialize a URLon the rule’s location.
- If the rule’s associated media list is not empty, a single SPACE (U+0020) followed by the result of performingserialize a media query liston the media list.
- The string "
;
",i.e., SEMICOLON (U+003B).
- The string "
CSSMediaRule
-
The result of concatenating the following:
- The string "
@media
",followed by a single SPACE (U+0020). - The result of performingserialize a media query liston rule’s media query list.
- A single SPACE (U+0020), followed by the string "{", i.e., LEFT CURLY BRACKET (U+007B), followed by a newline.
- The result of performingserialize a CSS ruleon each rule in the rule’s
cssRules
list, separated by a newline and indented by two spaces. - A newline, followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D)
- The string "
CSSFontFaceRule
-
The result of concatenating the following:
- The string "
@font-face {
",followed by a single SPACE (U+0020). - The string "
font-family:
",followed by a single SPACE (U+0020). - The result of performingserialize a stringon the rule’s font family name.
- The string "
;
",i.e., SEMICOLON (U+003B). -
If the rule’s associated source list is not empty, follow these substeps:
- A single SPACE (U+0020), followed by the string "
src:
",followed by a single SPACE (U+0020). - The result of invokingserialize a comma-separated liston performingserialize a URLorserialize a LOCALfor each source on the source list.
- The string "
;
",i.e., SEMICOLON (U+003B).
- A single SPACE (U+0020), followed by the string "
- If rule’s associatedunicode-rangedescriptor is present, a single
SPACE (U+0020), followed by the string "
unicode-range:
",followed by a single SPACE (U+0020), followed by the result of performing serialize a<'unicode-range'>,followed by the string ";
",i.e., SEMICOLON (U+003B). - If rule’s associatedfont-variantdescriptor is present, a single
SPACE (U+0020), followed by the string "
font-variant:
",followed by a single SPACE (U+0020), followed by the result of performing serialize a<'font-variant'>,followed by the string ";
",i.e., SEMICOLON (U+003B). - If rule’s associatedfont-feature-settingsdescriptor is present, a
single SPACE (U+0020), followed by the string "
font-feature-settings:
",followed by a single SPACE (U+0020), followed by the result of performing serialize a<'font-feature-settings'>,followed by the string ";
",i.e., SEMICOLON (U+003B). - If rule’s associatedfont-stretchdescriptor is present, a single
SPACE (U+0020), followed by the string "
font-stretch:
",followed by a single SPACE (U+0020), followed by the result of performing serialize a<'font-stretch'>,followed by the string ";
",i.e., SEMICOLON (U+003B). - If rule’s associatedfont-weightdescriptor is present, a single SPACE
(U+0020), followed by the string "
font-weight:
",followed by a single SPACE (U+0020), followed by the result of performing serialize a<'font-weight'>,followed by the string ";
",i.e., SEMICOLON (U+003B). - If rule’s associatedfont-styledescriptor is present, a single SPACE
(U+0020), followed by the string "
font-style:
",followed by a single SPACE (U+0020), followed by the result of performing serialize a<'font-style'>,followed by the string ";
",i.e., SEMICOLON (U+003B). - A single SPACE (U+0020), followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D).
Need to define how the
CSSFontFaceRule
descriptors' values are serialized. - The string "
CSSPageRule
-
Need to define how
CSSPageRule
is serialized. CSSNamespaceRule
- The literal string "
@namespace
",followed by a single SPACE (U+0020), followed by theserialization as an identifierof theprefix
attribute (if any), followed by a single SPACE (U+0020) if there is a prefix, followed by theserialization as URLof thenamespaceURI
attribute, followed the character ";
"(U+003B). CSSKeyframesRule
-
The result of concatenating the following:
- The literal string "
@keyframes
",followed by a single SPACE (U+0020). - Theserialization as an identifierof the
name
attribute. - The result of performingserialize a CSS ruleon each rule in the rule’s
cssRules
list, separated by a newline and indented by two spaces. - A newline, followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D)
- The literal string "
CSSKeyframeRule
-
The result of concatenating the following:
- The
keyText
. - The string "
{
",i.e., a single SPACE (U+0020), followed by LEFT CURLY BRACKET (U+007B), - The result of performingserialize a CSS declaration blockon 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).
- The
The "indented by two spaces" bit matches browsers, but needs work, see#5494
Toinsert a CSS rulerulein a CSS rule listlistat indexindex,follow these steps:
- Setlengthto the number of items inlist.
- Ifindexis greater thanlength,thenthrowan
IndexSizeError
exception. - Setnew ruleto the results of performingparse a CSS ruleon argumentrule.
- Ifnew ruleis a syntax error,throwa
SyntaxError
exception. -
Ifnew rulecannot be inserted intolistat the zero-index positionindexdue to constraints
specified by CSS, thenthrowa
HierarchyRequestError
exception.[CSS21]Note:For example, a CSS style sheet cannot contain an
@import
at-rule after a style rule. - Ifnew ruleis an
@namespace
at-rule, andlistcontains anything other than@import
at-rules, and@namespace
at-rules,throwanInvalidStateError
exception. - Insertnew ruleintolistat the zero-indexed positionindex.
- Returnindex.
Toremove a CSS rulefrom a CSS rule listlistat indexindex,follow these steps:
- Setlengthto the number of items inlist.
- Ifindexis greater than or equal tolength,thenthrowan
IndexSizeError
exception. - Setold ruleto theindexth item inlist.
- Ifold ruleis an
@namespace
at-rule, andlistcontains anything other than@import
at-rules, and@namespace
at-rules,throwanInvalidStateError
exception. - Remove ruleold rulefromlistat the zero-indexed positionindex.
- Setold rule’sparent CSS ruleandparent CSS style sheetto null.
6.4.1.TheCSSRuleList
Interface
TheCSSRuleList
interface represents an ordered collection of CSS style rules.
[Exposed =Window ]interface {
CSSRuleList getter CSSRule ?item (unsigned long );
index readonly attribute unsigned long length ; };
The object’ssupported property indicesare the numbers in the range zero to one less than the number ofCSSRule
objects represented by the collection. If there are no suchCSSRule
objects, then there are nosupported property indices.
Theitem(index)
method must return theindexthCSSRule
object in the collection. If there is noindexth object in the collection, then the method must return null.
Thelength
attribute must return the number ofCSSRule
objects represented by the
collection.
6.4.2.TheCSSRule
Interface
TheCSSRule
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.
[Exposed =Window ]interface {
CSSRule attribute CSSOMString cssText ;readonly attribute CSSRule ?parentRule ;readonly attribute CSSStyleSheet ?parentStyleSheet ; // the following attribute and constants are historicalreadonly attribute unsigned short type ;const unsigned short = 1;
STYLE_RULE const unsigned short = 2;
CHARSET_RULE const unsigned short = 3;
IMPORT_RULE const unsigned short = 4;
MEDIA_RULE const unsigned short = 5;
FONT_FACE_RULE const unsigned short = 6;
PAGE_RULE const unsigned short = 9;
MARGIN_RULE const unsigned short = 10; };
NAMESPACE_RULE
ThecssText
attribute must return aserializationof theCSS rule.
On setting thecssText
attribute must do nothing.
TheparentRule
attribute must return theparent CSS
rule.
Note:For example,@media
can enclose a rule, in which caseparentRule
would
be non-null; in cases where there is no enclosing rule,parentRule
will be null.
TheparentStyleSheet
attribute must return theparent CSS style sheet.
Note:The only circumstance where null is returned when a rule has beenremoved.
Note:Removing aNode
that implements theLinkStyle
interface from aDocument
instance does not (by itself) cause theCSSStyleSheet
referenced by aCSSRule
to be
unreachable.
Thetype
attribute is deprecated.
It must return an integer, as follows:
- If the object is a
CSSStyleRule
- Return 1.
- If the object is a
CSSImportRule
- Return 3.
- If the object is a
CSSMediaRule
- Return 4.
- If the object is a
CSSFontFaceRule
- Return 5.
- If the object is a
CSSPageRule
- Return 6.
- If the object is a
CSSKeyframesRule
- Return 7.
- If the object is a
CSSKeyframeRule
- Return 8.
- If the object is a
CSSMarginRule
- Return 9.
- If the object is a
CSSNamespaceRule
- Return 10.
- If the object is a
CSSCounterStyleRule
- Return 11.
- If the object is a
CSSSupportsRule
- Return 12.
- If the object is a
CSSFontFeatureValuesRule
- Return 14.
- If the object is a
CSSViewportRule
- Return 15.
- Otherwise
- Return 0.
Note:The practice of using an integer enumeration
and several constants toidentifythe integers
is a legacy design practice that is no longer used in Web APIs.
Instead, to tell what type of rule a given object is,
it is recommended to checkrule
,
which will return a string like
.
6.4.3.TheCSSStyleRule
Interface
TheCSSStyleRule
interface represents a style rule.
[Exposed =Window ]interface :
CSSStyleRule CSSRule {attribute CSSOMString selectorText ; [SameObject ,PutForwards =cssText ]readonly attribute CSSStyleDeclaration style ; };
TheselectorText
attribute, on getting, must return the result ofserializingthe associatedgroup of selectors.
On setting theselectorText
attribute these steps must be run:
- Run theparse a group of selectorsalgorithm on the given value.
- If the algorithm returns a non-null value replace the associatedgroup of selectorswith the returned value.
- Otherwise, if the algorithm returns a null value, do nothing.
Thestyle
attribute must return aCSSStyleDeclaration
object for the style rule, with the
following properties:
- computed flag
- Unset.
- declarations
- The declared declarations in the rule, inspecified order.
- parent CSS rule
- Thecontext object.
- owner node
- Null.
Thespecified orderfor 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.[CSS3CASCADE]
6.4.4.TheCSSImportRule
Interface
TheCSSImportRule
interface represents an@import
at-rule.
[Exposed =Window ]interface :
CSSImportRule CSSRule {readonly attribute USVString href ; [SameObject ,PutForwards =mediaText ]readonly attribute MediaList media ; [SameObject ]readonly attribute CSSStyleSheet styleSheet ; };
Thehref
attribute must return theURLspecified by
the@import
at-rule.
Note:To get the resolvedURLuse thehref
attribute of the associatedCSS style sheet.
Themedia
attribute must return the value of themedia
attribute of the associatedCSS style sheet.
ThestyleSheet
attribute must return the associatedCSS style sheet.
Note:An@import
at-rule always has an associatedCSS style sheet.
6.4.5.TheCSSGroupingRule
Interface
TheCSSGroupingRule
interface represents an at-rule that contains other rules nested inside itself.
[Exposed =Window ]interface :
CSSGroupingRule CSSRule { [SameObject ]readonly attribute CSSRuleList cssRules ;unsigned long insertRule (CSSOMString ,
rule optional unsigned long = 0);
index undefined deleteRule (unsigned long ); };
index
ThecssRules
attribute must return aCSSRuleList
object for thechild CSS rules.
TheinsertRule(rule,index)
method must return the result of
invokinginsert a CSS ruleruleinto thechild CSS rulesatindex.
ThedeleteRule(index)
method mustremove a CSS rulefrom thechild CSS rulesatindex.
6.4.6.TheCSSMediaRule
Interface
TheCSSMediaRule
interface is defined inCSS Conditional Rules.[CSS3-CONDITIONAL]
6.4.7.TheCSSPageRule
Interface
TheCSSPageRule
interface represents an@page
at-rule.
Need to define the rules forparse a list of CSS page selectorsandserialize a list of CSS page selectors.
[Exposed =Window ]interface :
CSSPageRule CSSGroupingRule {attribute CSSOMString ; [
selectorText SameObject ,PutForwards =cssText ]readonly attribute CSSStyleDeclaration ; };
style
TheselectorText
attribute, on getting, must return the result ofserializingthe associatedlist of CSS page selectors.
On setting theselectorText
attribute these steps must be run:
- Run theparse a list of CSS page selectorsalgorithm on the given value.
- If the algorithm returns a non-null value replace the associatedlist of CSS page selectorswith the returned value.
- Otherwise, if the algorithm returns a null value, do nothing.
Thestyle
attribute must return aCSSStyleDeclaration
object for the@page
at-rule, with the following properties:
- computed flag
- Unset.
- declarations
- The declared declarations in the rule, inspecified order.
- parent CSS rule
- Thecontext object.
- owner node
- Null.
6.4.8.TheCSSMarginRule
Interface
TheCSSMarginRule
interface represents a margin at-rule (e.g.@top-left
) in an@page
at-rule.[CSS3PAGE]
[Exposed =Window ]interface :
CSSMarginRule CSSRule {readonly attribute CSSOMString name ; [SameObject ,PutForwards =cssText ]readonly attribute CSSStyleDeclaration style ; };
Thename
attribute must return the name of the margin at-rule. The@
character is not
included in the name.[CSS3SYN]
Thestyle
attribute must return aCSSStyleDeclaration
object for the
margin at-rule, with the following properties:
- computed flag
- Unset.
- declarations
- The declared declarations in the rule, inspecified order.
- parent CSS rule
- Thecontext object.
- owner node
- Null.
6.4.9.TheCSSNamespaceRule
Interface
TheCSSNamespaceRule
interface represents an@namespace
at-rule.
[Exposed =Window ]interface :
CSSNamespaceRule CSSRule {readonly attribute CSSOMString namespaceURI ;readonly attribute CSSOMString prefix ; };
ThenamespaceURI
attribute must return the namespace of the@namespace
at-rule.
Theprefix
attribute must return the prefix of the@namespace
at-rule or the
empty string if there is no prefix.
6.5.CSS Declarations
ACSS declarationis an abstract concept that is not exposed as an object in the DOM. ACSS declarationhas 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 theproperty nameis defined to be case-sensitive according to its specification, otherwise unset.
6.6.CSS Declaration Blocks
ACSS declaration blockis an ordered collection of CSS
properties with their associated values, also namedCSS declarations.In
the DOM aCSS declaration blockis aCSSStyleDeclaration
object. ACSS declaration blockhas the following associated properties:
- computed flag
- Set if the object is a computed style declaration, rather than a specified style. Unless otherwise stated it is unset.
- declarations
- TheCSS declarationsassociated with the object.
- parent CSS rule
- TheCSS rulethat theCSS declaration blockis associated with, if any, or null otherwise.
- owner node
- The
Element
that theCSS declaration blockis associated with, if any, or null otherwise. - updating flag
- Unset by default. Set when theCSS declaration blockis updating
theowner node’s
style
attribute.
Toparse a CSS declaration blockfrom a stringstring,follow these steps:
- Letdeclarationsbe the return value of invokingparse a list of declarationswithstring.
- Letparsed declarationsbe a new empty list.
-
For each itemdeclarationindeclarations,follow these substeps:
- Letparsed declarationbe the result of parsingdeclarationaccording to the appropriate CSS specifications, dropping parts that are said to be ignored. If the whole declaration is dropped, letparsed declarationbe null.
- Ifparsed declarationis not null, append it toparsed declarations.
- Returnparsed declarations.
Toserialize a CSS declarationwith property nameproperty,valuevalueand optionally animportantflag set, follow these steps:
- Letsbe the empty string.
- Appendpropertytos.
- Append "
:
"(U+003A U+0020) tos. - Appendvaluetos.
- If theimportantflag 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) tos. - Append "
;
"(U+003B) tos. - Returns.
Toserialize a CSS declaration blockdeclaration blockmeans to run the steps below:
- Letlistbe an empty array.
- Letalready serializedbe an empty array.
-
Declaration loop:For eachCSS declarationdeclarationindeclaration block’sdeclarations,follow these substeps:
- Letpropertybedeclaration’sproperty name.
- Ifpropertyis inalready serialized,continue with the steps labeleddeclaration loop.
- Ifpropertymaps to one or more shorthand properties, letshorthandsbe an array of those shorthand properties, inpreferred order.
-
Shorthand loop:For eachshorthandinshorthands,follow these substeps:
- Letlonghandsbe an array consisting of allCSS declarationsindeclaration block’sdeclarationsthat that are not inalready serializedand have aproperty namethat maps to one of the shorthand properties inshorthands.
- If all properties that map toshorthandare not present inlonghands,continue with the steps labeledshorthand loop.
- Letcurrent longhandsbe an empty array.
- Append allCSS declarationsinlonghandsthat have aproperty namethat maps toshorthandtocurrent longhands.
- If there is one or moreCSS declarationsincurrent longhandshave theirimportant flagset and one or more with it unset, continue with the steps labeledshorthand loop.
- If there’s any declaration indeclaration blockin between the first and the last longhand incurrent longhandswhich belongs to the samelogical property group,but has a differentmapping logicas any of the longhands incurrent longhands, and is not incurrent longhands,continue with the steps labeledshorthand loop.
- Letvaluebe the result of invokingserialize a CSS valueofcurrent longhands.
- Ifvalueis the empty string, continue with the steps labeledshorthand loop.
- Letserialized declarationbe the result of invokingserialize a CSS declarationwith property nameshorthand,valuevalue,and theimportantflag set if theCSS declarationsincurrent longhandshave theirimportant flagset.
- Appendserialized declarationtolist.
- Append the property names of all items ofcurrent longhandstoalready serialized.
- Continue with the steps labeleddeclaration loop.
- Letvaluebe the result of invokingserialize a CSS valueofdeclaration.
- Letserialized declarationbe the result of invokingserialize a CSS declarationwith property nameproperty,valuevalue,and theimportantflag set ifdeclarationhas itsimportant flagset.
- Appendserialized declarationtolist.
- Appendpropertytoalready serialized.
- Returnlistjoined with "
"(U+0020).
Note:The serialization of an empty CSS declaration block is the empty string.
Note:The serialization of a non-empty CSS declaration block does not include any surrounding whitespace, i.e., no whitespace appears before the first property name and no whitespace appears after the final semicolon delimiter that follows the last property value.
ACSS declaration blockhas theseattribute change stepsfor itsowner nodewithlocalName,value,andnamespace:
- If thecomputed flagis set, then return.
- If theupdating flagis set, then return.
- IflocalNameis not "
style
",ornamespaceis not null, then return. - Ifvalueis null, empty thedeclarations.
- Otherwise, let thedeclarationsbe the result ofparse a CSS declaration blockfrom a stringvalue.
When aCSS declaration blockobject is created, then:
- Letowner nodebe theowner node.
- Ifowner nodeis null, or thecomputed flagis set, then return.
- Letvaluebe the result ofgetting an attributegiven null, "
style
",andowner node. - Ifvalueis not null, let thedeclarationsbe the result ofparse a CSS declaration blockfrom a stringvalue.
Toupdate style attribute fordeclaration blockmeans to run the steps below:
- Assert:declaration block’scomputed flagis unset.
- Letowner nodebedeclaration block’sowner node.
- Ifowner nodeis null, then return.
- Setdeclaration block’supdating flag.
- Set an attribute valueforowner nodeusing "
style
"and the result ofserializingdeclaration block. - Unsetdeclaration block’supdating flag.
Thepreferred orderof a list of shorthand propertiesshorthandsis as follows:
- Ordershorthandslexicographically.
- Move all items inshorthandsthat begin with "
-
"(U+002D) last in the list, retaining their relative order. - Move all items inshorthandsthat begin with "
-
"(U+002D) but do not begin with"-webkit-
"last in the list, retaining their relative order. - Ordershorthandsby the number of longhand properties that map to it, with the greatest number first.
6.6.1.TheCSSStyleDeclaration
Interface
TheCSSStyleDeclaration
interface represents aCSS declaration block,including its underlying state, where this
underlying state depends upon the source of theCSSStyleDeclaration
instance.
[Exposed =Window ]interface { [
CSSStyleDeclaration CEReactions ]attribute CSSOMString cssText ;readonly attribute unsigned long length ;getter CSSOMString item (unsigned long );
index CSSOMString getPropertyValue (CSSOMString );
property CSSOMString getPropertyPriority (CSSOMString ); [
property CEReactions ]undefined setProperty (CSSOMString ,[
property LegacyNullToEmptyString ]CSSOMString ,
value optional [LegacyNullToEmptyString ]CSSOMString = "" ); [
priority CEReactions ]CSSOMString removeProperty (CSSOMString );
property readonly attribute CSSRule ?parentRule ; [CEReactions ]attribute [LegacyNullToEmptyString ]CSSOMString cssFloat ; };
The object’ssupported property indicesare the numbers in the range zero to one less than the number ofCSS declarationsin thedeclarations.If there are no suchCSS declarations,then there are nosupported property indices.
Getting thecssText
attribute must run these steps:
-
If thecomputed flagis set, then return the empty string.
-
Return the result ofserializingthedeclarations.
Setting thecssText
attribute must run these steps:
- If thecomputed flagis set,
thenthrowa
NoModificationAllowedError
exception. - Empty thedeclarations.
- Parsethe given value and, if the return value is not the empty list, insert the items in the list into thedeclarations,inspecified order.
- Update style attribute fortheCSS declaration block.
Thelength
attribute must return the number ofCSS
declarationsin thedeclarations.
Theitem(index)
method must return theproperty nameof theCSS declarationat positionindex.
ThegetPropertyValue(property)
method must run these steps:
-
Ifpropertyis not acustom property,follow these substeps:
- Letpropertybepropertyconverted to ASCII lowercase.
-
Ifpropertyis a shorthand property, then follow these substeps:
- Letlistbe a new empty array.
-
For each longhand propertylonghandthatpropertymaps to, in canonical order, follow these substeps:
- Iflonghandis acase-sensitivematch for aproperty nameof aCSS declarationin thedeclarations,letdeclarationbe thatCSS declaration,or null otherwise.
- Ifdeclarationis null, then return the empty string.
- Append thedeclarationtolist.
- Ifimportant flagsof all declarations inlistare same, then return theserializationoflist.
- Return the empty string.
- Ifpropertyis acase-sensitivematch for aproperty nameof aCSS declarationin thedeclarations,then return the result of invokingserialize a CSS valueof that declaration.
- Return the empty string.
ThegetPropertyPriority(property)
method must run these steps:
-
Ifpropertyis not acustom property,follow these substeps:
- Letpropertybepropertyconverted to ASCII lowercase.
-
Ifpropertyis a shorthand property, follow these substeps:
- Letlistbe a new array.
- For each longhand propertylonghandthatpropertymaps to, append the result of invoking
getPropertyPriority()
withlonghandas argument tolist. - If all items inlistare the string "
important
",then return the string"important
".
- Ifpropertyis acase-sensitivematch for aproperty nameof aCSS
declarationin thedeclarationsthat has theimportant flagset, return the string "
important
". - Return the empty string.
ThesetProperty(property,value,priority)
method must run these steps:
- If thecomputed flagis set,
thenthrowa
NoModificationAllowedError
exception. -
Ifpropertyis not acustom property,follow these substeps:
- Letpropertybepropertyconverted to ASCII lowercase.
- Ifpropertyis not acase-sensitivematch for asupported CSS property,then return.
- Ifvalueis the empty string, invoke
removeProperty()
withpropertyas argument and return. - Ifpriorityis not the empty string and is not anASCII case-insensitivematch for the string
"
important
",then return. -
Letcomponent value listbe the result ofparsingvaluefor propertyproperty.
Note:valuecan not include "
!important
". - Ifcomponent value listis null, then return.
- Letupdatedbe false.
-
Ifpropertyis a shorthand property, then for each longhand propertylonghandthatpropertymaps to, in canonical
order, follow these substeps:
- Letlonghand resultbe the result ofset the CSS declarationlonghandwith the appropriate value(s) fromcomponent value list,with theimportantflag set ifpriorityis not the empty string, and unset otherwise, and with the list of declarations being thedeclarations.
- Iflonghand resultis true, letupdatedbe true.
- Otherwise, letupdatedbe the result ofset the CSS declarationpropertywith valuecomponent value list,with theimportantflag set ifpriorityis not the empty string, and unset otherwise, and with the list of declarations being thedeclarations.
- Ifupdatedis true,update style attribute fortheCSS declaration block.
Toset a CSS declarationpropertywith a valuecomponent value listand optionally with animportantflag set, in a list of declarationsdeclarations,the user agent must ensure the following constraints hold after its steps:
- Exactly oneCSS declarationwhoseproperty nameis acase-sensitivematch ofpropertymust exist indeclarations. Such declaration is referenced as thetarget declarationbelow.
- Thetarget declarationmust have value beingcomponent value list, andtarget declaration’simportant flagmust besetifimportantflag is set, andunsetotherwise.
- AnyCSS declarationwhich is not thetarget declarationmust not be changed, inserted, or removed fromdeclarations.
- If there areCSS declarationsindeclarationswhoseproperty nameis in the samelogical property groupasproperty,but has a differentmapping logic,target declarationmust be at an index after all of thoseCSS declarations.
- The steps must return true if the serialization ofdeclarationswas changed as result of the steps. It may return false otherwise.
Should we add something like "Any observable side effect must not be made outsidedeclarations"?The current constraints sound like a hole for undefined behavior.
Note:The steps ofset a CSS declarationare not defined in this level of CSSOM. User agents may use different algorithms as long as the constraints above hold.
Another possible algorithm is:
-
Ifpropertyis acase-sensitivematch for aproperty nameof aCSS declarationindeclarations,follow these substeps:
- Lettarget declarationbe suchCSS declaration.
- Letneeds appendbe false.
-
For eachdeclarationindeclarationsaftertarget declaration:
- Ifdeclaration’sproperty nameis not in the samelogical property groupasproperty,thencontinue.
- Ifdeclaration’property namehas the samemapping logicasproperty,thencontinue.
- Letneeds appendbe true.
- Break.
-
Ifneeds appendis false, then:
- Letneeds updatebe false.
- Iftarget declaration’svalueis not equal tocomponent value list,then letneeds updatebe true.
- Iftarget declaration’simportant flagis not equal to whetherimportantflag is set, then letneeds updatebe true.
- Ifneeds updateis false, then return false.
- Settarget declaration’svaluetocomponent value list.
- Ifimportantflag is set, then settarget declaration’simportant flag,otherwise unset it.
- Return true.
- Otherwise, removetarget declarationfromdeclarations.
- Append a newCSS declarationwithproperty nameproperty,valuecomponent value list,andimportant flagset ifimportantflag is set todeclarations.
- Return true.
TheremoveProperty(property)
method must run these steps:
- If thecomputed flagis set,
thenthrowa
NoModificationAllowedError
exception. - Ifpropertyis not acustom property, letpropertybepropertyconverted to ASCII lowercase.
- Letvaluebe the return value of invoking
getPropertyValue()
withpropertyas argument. - Letremovedbe false.
-
Ifpropertyis a shorthand property, for each longhand propertylonghandthatpropertymaps to:
- Iflonghandis not aproperty nameof aCSS declarationin thedeclarations,continue.
- Remove thatCSS declarationand letremovedbe true.
- Otherwise, ifpropertyis acase-sensitivematch for aproperty nameof aCSS declarationin thedeclarations,remove thatCSS declarationand letremovedbe true.
- Ifremovedis true,Update style attribute fortheCSS declaration block.
- Returnvalue.
TheparentRule
attribute must return theparent CSS rule.
ThecssFloat
attribute, on getting, must return the result of invokinggetPropertyValue()
withfloat
as argument. On setting, the attribute must invokesetProperty()
withfloat
as first argument, as second argument the given value, and no third argument.
Any exceptions thrown must be re-thrown.
For each CSS propertypropertythat is asupported CSS property,
the following partial interface applies wherecamel-cased attribute
is obtained by running theCSS property to IDL attributealgorithm forproperty.
partial interface CSSStyleDeclaration { [CEReactions ]attribute [LegacyNullToEmptyString ]CSSOMString ; };
_camel_cased_attribute
Thecamel-cased attributeattribute, on getting, must return the
result of invokinggetPropertyValue()
with the
argument being the result of running theIDL attribute to CSS propertyalgorithm forcamel-cased attribute.
Setting thecamel-cased attributeattribute must invokesetProperty()
with the
first argument being the result of running theIDL attribute to CSS propertyalgorithm forcamel-cased attribute,as second argument the given value, and no third argument. Any
exceptions thrown must be re-thrown.
For each CSS propertypropertythat is asupported CSS propertyand that begins
with the string-webkit-
,the following partial interface applies wherewebkit-cased attributeis obtained by running theCSS property to IDL attributealgorithm forproperty,with thelowercase firstflag set.
partial interface CSSStyleDeclaration { [CEReactions ]attribute [LegacyNullToEmptyString ]CSSOMString ; };
_webkit_cased_attribute
Thewebkit-cased attribute
attribute, on
getting, must return the result of invokinggetPropertyValue()
with the
argument being the result of running theIDL attribute to CSS propertyalgorithm forwebkit-cased attribute,with thedash prefixflag set.
Setting thewebkit-cased attributeattribute must invokesetProperty()
with the first argument being the result
of running theIDL attribute to CSS propertyalgorithm forwebkit-cased attribute,
with thedash prefixflag set, as second argument the given value, and no third argument.
Any exceptions thrown must be re-thrown.
webkitTransform
IDL attribute. There would also be aWebkitTransform
IDL attribute because of the rules for camel-cased attributes.For each CSS propertypropertythat is asupported CSS property,
except for properties that have no "-
"(U+002D) in the property name,
the following partial interface applies wheredashed attributeisproperty.
partial interface CSSStyleDeclaration { [CEReactions ]attribute [LegacyNullToEmptyString ]CSSOMString ; };
_dashed_attribute
Thedashed attribute
attribute, on getting, must return the
result of invokinggetPropertyValue()
with the
argument beingdashed attribute.
Setting thedashed attributeattribute must invokesetProperty()
with the
first argument beingdashed attribute,as second argument the given value, and no third argument. Any
exceptions thrown must be re-thrown.
font-size
IDL attribute. In JavaScript, the property can be accessed as
follows, assumingelementis anHTML element:
element.style['font-size'];
TheCSS property to IDL attributealgorithm forproperty,optionally with alowercase firstflag set, is as follows:
- Letoutputbe the empty string.
- Letuppercase nextbe unset.
- If thelowercase firstflag is set, remove the first character fromproperty.
-
For each charactercinproperty:
- Ifcis "
-
"(U+002D), letuppercase nextbe set. - Otherwise, ifuppercase nextis set, letuppercase nextbe unset and appendcconverted to ASCII uppercasetooutput.
- Otherwise, appendctooutput.
- Ifcis "
- Returnoutput.
TheIDL attribute to CSS propertyalgorithm forattribute,optionally with adash prefixflag set, is as follows:
- Letoutputbe the empty string.
- If thedash prefixflag is set, append "
-
"(U+002D) tooutput. -
For each charactercinattribute:
- Ifcis in the range U+0041 to U+005A (ASCII uppercase), append "
-
"(U+002D) followed bycconverted to ASCII lowercasetooutput. - Otherwise, appendctooutput.
- Ifcis in the range U+0041 to U+005A (ASCII uppercase), append "
- Returnoutput.
6.7.CSS Values
6.7.1.Parsing CSS Values
Toparse a CSS valuevaluefor a givenpropertymeans to follow these steps:
- Letlistbe the value returned by invokingparse a list of component valuesfromvalue.
- Matchlistagainst the grammar for the propertypropertyin the CSS specification.
- If the above step failed, return null.
- Returnlist.
Note:"!important
"declarations are not
part of the property value space and will therefore causeparse a CSS valueto return null.
6.7.2.Serializing CSS Values
Toserialize a CSS valueof aCSS declarationdeclarationor a list of longhandCSS declarationslist, follow these rules:
-
If this algorithm is invoked with alistlist:
-
Letshorthandbe the first shorthand property, inpreferred order, that exactly maps to all of the longhand properties inlist.
-
If there is no such shorthand orshorthandcannot exactly represent the values of all the properties inlist, return the empty string.
-
Otherwise,serialize a CSS valuefrom a hypothetical declaration of the propertyshorthandwith its value representing the combined values of the declarations inlist.
-
-
Represent the value of thedeclarationas alistof CSS component valuescomponentsthat, whenparsedaccording to the property’s grammar, would represent that value. Additionally:
-
If certain component values can appear in any order without changing the meaning of the value (a pattern typically represented by a double bar||in the value syntax), reorder the component values to use the canonical order of component values as given in the property definition table.
-
If component values can be omitted or replaced with a shorter representation without changing the meaning of the value, omit/replace them.
-
If either of the above syntactic translations would be less backwards-compatible, do not perform them.
Note:The rules described here outlines thegeneral principlesof serialization. For legacy reasons, some properties serialize in a different manner, which is intentionally undefined here due to lack of resources. Please consult your local reverse-engineer for details.
-
-
Remove any<whitespace-token>s fromcomponents.
-
Replace each component value incomponentswith the result of invokingserialize a CSS component value.
-
Join the items ofcomponentsinto a single string, inserting "" (U+0020 SPACE) between each pair of items unless the second item is a "," (U+002C COMMA) Return the result.
Toserialize a CSS component valuedepends on the component, as follows:
- keyword
- The keywordconverted to ASCII lowercase.
- <angle>
-
The <number> component serialized as per <number> followed by the unit in canonical form as defined in its respective specification.
Probably should distinguish between specified and computed / resolved values.
- <color>
-
If <color> is a component of a resolved value, seeCSS Color 4§ 4.6 Resolving <color> Values.
If <color> is a component of a computed value, seeCSS Color 4§ 4.7 Serializing <color> Values.
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, the same as computed values? Or should original case be preserved?
- <alphavalue>
-
If the value is internally represented as an integer between 0 and 255 inclusive (i.e. 8-bit unsigned integer),
follow these steps:
- Letalphabe the given integer.
- If there exists an integer between 0 and 100 inclusive that, when multiplied with 2.55 and rounded to the closest integer (rounding up if two values are equally close), equalsalpha, letroundedbe that integer divided by 100.
- Otherwise, letroundedbealphadivided by 0.255 and rounded to the closest integer (rounding up if two values are equally close), divided by 1000.
- Return the result of serializingroundedas a <number>.
Otherwise, return the result of serializing the given value as a <number>.
- <counter>
-
The return value of the following algorithm:
- Letsbe the empty string.
- If <counter> has three CSS component values append the string
"
counters(
"tos. - If <counter> has two CSS component values append the string
"
counter(
"tos. - Letlistbe a list of CSS component values belonging to <counter>, omitting the last CSS component value if it is "decimal".
- Let each item inlistbe the result of invokingserialize a CSS component valueon that item.
- Append the result of invokingserialize a comma-separated listonlisttos.
- Append "
)
"(U+0029) tos. - Returns.
- <frequency>
-
The <number> component serialized as per <number> followed by the unit in its canonical form as defined in its respective specification.
Probably should distinguish between specified and computed / resolved values.
- <identifier>
- The identifierserialized as an identifier.
- <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>
-
The <number> component serialized as per <number> followed by the unit in its canonical form as defined in its respective specification.
Probably should distinguish between specified and computed / resolved values.
- <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), rounding the value if necessary to not produce more than 6 decimals, preceded by"-
"(U+002D) if it is negative.Note:scientific notation is not used.
- <percentage>
- The <number> component serialized as per <number> followed
by the literal string "
%
"(U+0025). - <resolution>
- The resolution in dots perCSS pixelserialized as per
<number> followed by the literal string "
dppx
". - <ratio>
- The numerator serialized as per <number>
followed by the literal string "
/
", followed by the denominator serialized as per <number>. - <shape>
-
The return value of the following algorithm:
- Letsbe the string "
rect(
". - Letlistbe a list of the CSS component values belonging to <shape>.
- Let each item inlistbe the result of invokingserialize a CSS component valueof that item.
- Append the result of invokingserialize a comma-separated listonlisttos.
- Append "
)
"(U+0029) tos. - Returns.
- Letsbe the string "
- <string>
- <family-name>
- <specific-voice>
- <family-name>
- The stringserialized as a string.
- <time>
- The time in seconds serialized as per <number> followed by
the literal string "
s
". - <url>
-
Theabsolute-URL stringserialized as URL.
This should differentiate specified and computed<url>values, see#3195.
<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
|
7.DOM Access to CSS Declaration Blocks
7.1.TheElementCSSInlineStyle
Mixin
TheElementCSSInlineStyle
mixin provides access to inline style properties of an element.
interface mixin { [
ElementCSSInlineStyle SameObject ,PutForwards =cssText ]readonly attribute CSSStyleDeclaration style ; };
Thestyle
attribute must return aCSS declaration blockobject whosecomputed flagis unset, whoseparent CSS ruleis null, and
whoseowner nodeis thecontext object.
If the user agent supports HTML, the following IDL applies:[HTML]
HTMLElement includes ElementCSSInlineStyle ;
If the user agent supports SVG, the following IDL applies:[SVG11]
SVGElement includes ElementCSSInlineStyle ;
If the user agent supports MathML, the following IDL applies:[MathML-Core]
MathMLElement includes ElementCSSInlineStyle ;
7.2.Extensions to theWindow
Interface
partial interface Window { [NewObject ]CSSStyleDeclaration getComputedStyle (Element ,
elt optional CSSOMString ?); };
pseudoElt
ThegetComputedStyle(elt,pseudoElt)
method must run these
steps:
- Letdocbeelt’snode document.
- Letobjbeelt.
-
IfpseudoEltis provided, and it’s not the empty string, then:
- ParsepseudoEltas a<pseudo-element-selector>,and lettypebe the result.
- Iftypeis failure, or is an::slotted()or::part()pseudo-element,throwa
TypeError
exception. - Otherwise letobjbe the given pseudo-element ofelt.
Note:CSS2 pseudo-elements should match both the double and single-colon versions. That is, both
:before
and::before
should match above. - Letdeclsbe an empty list ofCSS declarations.
-
Ifeltisconnected,part of theflat tree,
and itsshadow-including roothas abrowsing contextwhich either
doesn’t have abrowsing context container,or whosebrowsing context containerisbeing rendered,
setdeclsto a list of all longhand properties that aresupported CSS properties,in lexicographical order,
with the value being theresolved valuecomputed forobjusing the style rules associated withdoc.Additionally, append todeclsall thecustom propertieswhosecomputed valueforobjis not theguaranteed-invalid value.
There are UAs that handle shorthands, and all UAs handle shorthands that used to be longhands likeoverflow,see#2529.
Order of custom properties is currently undefined, see#4947.
-
Return a liveCSS declaration blockwith the following properties:
- computed flag
- Set.
- declarations
- decls.
- parent CSS rule
- Null.
- owner node
- obj.
ThegetComputedStyle()
method exposes information fromCSS style
sheetswith theorigin-clean flagunset.
Should getComputedStyle() provide a useful serialization? See#1033
8.Utility APIs
8.1.TheCSS.escape()
Method
TheCSS
namespace holds useful CSS-related functions that do not belong elsewhere.
[Exposed =Window ]namespace {
CSS CSSOMString escape (CSSOMString ); };
ident
This was previously specified as an IDL interface that only held static methods. Switching to an IDL namespace is *nearly* identical, so it’s expected that there won’t be any compat concerns. If any are discovered, please report so we can consider reverting this change.
Theescape(ident)
operation must return the result of invokingserialize an identifierofident.
escape()
method can be used:
var element = document.querySelector('#' + CSS.escape(id) + ' > img');
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) + '" ]');
Specifications that define operations on theCSS
namespace and want to
store some state should store the state on thecurrent global
object’sassociatedDocument
.
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 ofgetComputedStyle()
had to
remain the same for compatibility with deployed scripts. To address this
issue this specification introduces the concept of aresolved value.
Theresolved valuefor a given longhand property can be determined as follows:
- background-color
- border-block-end-color
- border-block-start-color
- border-bottom-color
- border-inline-end-color
- border-inline-start-color
- border-left-color
- border-right-color
- border-top-color
- box-shadow
- caret-color
- color
- outline-color
- Aresolved value special case property likecolordefined in another specification
- border-block-end-color
- Theresolved valueis theused value.
- line-height
- Theresolved valueisnormalif thecomputed valueisnormal,or theused valueotherwise.
- block-size
- height
- inline-size
- margin-block-end
- margin-block-start
- margin-bottom
- margin-inline-end
- margin-inline-start
- margin-left
- margin-right
- margin-top
- padding-block-end
- padding-block-start
- padding-bottom
- padding-inline-end
- padding-inline-start
- padding-left
- padding-right
- padding-top
- width
- Aresolved value special case property likeheightdefined in another specification
- height
- If the property applies to the element or pseudo-element and theresolved valueof thedisplayproperty is notnoneorcontents,then theresolved valueis theused value.Otherwise theresolved valueis thecomputed value.
- bottom
- left
- inset-block-end
- inset-block-start
- inset-inline-end
- inset-inline-start
- right
- top
- Aresolved value special case property liketopdefined in another specification
- left
- If the property applies to a positioned element and theresolved valueof thedisplayproperty is notnoneorcontents,and the property is not over-constrained, then theresolved valueis theused value.Otherwise theresolved valueis thecomputed value.
- Aresolved value special case propertydefined in another specification
- As defined in the relevant specification.
- Any other property
- Theresolved valueis thecomputed 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.
11.Change History
This section documents some of the changes between publications of this specification. This section is not exhaustive. Bug fixes and editorial changes are generally not listed.
11.1.Changes From 17 March 2016
-
Serialization of<resolution>is changed.
-
[CEReactions]
IDL extended attributes are added. -
Resolved value for logical properties are added.
-
MediaList.item
now returns serialization. -
MediaList.item
does not serialize shorthand if importance differs. -
Other specifications are allowed to specify resolved value.
-
index
argument ininsertRule
is now optional. -
href
attribute ofStylesheet
andCSSImportRule
now usesUSVString
. -
CSSOMString
is introduced. -
Serialization of
CSSMediaRule
andCSSFontFaceRule
is added. -
Updating flagis added to CSS declaration block to avoid serialize-and-reparse on style attribute.
-
Serialization of a declaration value is now properly defined.
-
getComputedStyle
now returns the style rules of the node’s document. -
A
TypeError
is thrown when the pseudo-element passed togetComputedStyle
is unknown or::slotted(). -
CSS
is switched from interface to namespace. -
setPropertyValue
andsetPropertyPriority
are removed fromCSSStyleDeclaration
due to lack of interest from implementations. -
The
styleSheets
IDL attribute is moved fromDocument
toDocumentOrShadowRoot
. -
LinkStyle.sheet now returns
CSSStyleSheet
instead ofStyleSheet
-
Deprecated CSSStyleSheet members are defined.
-
The
CSSRule.type
attribute is deprecated. -
Serialization of<ratio>is added.
-
CSSStyleDeclaration.cssText
now returns the empty string for computed style. -
Custom propertiesare included in
getComputedStyle
. -
MathML IDL is introduced.
-
Serialization of
CSSKeyframesRule
andCSSKeyframeRule
is added. -
Serialization of media query is changed.
-
A shorthand is not serialized if there are longhands with other property group / mapping logic in between the longhands of that shorthand.
-
CSSStyleRule
serialization is aware of nesting now. -
Constructable stylesheets is introduced.
11.2.Changes From 5 December 2013
-
API for alternative stylesheets is removed:
selectedStyleSheetSet
,lastStyleSheetSet
,preferredStyleSheetSet
,styleSheetSets
,enableStyleSheetsForSet()
onDocument
. -
The
pseudo()
method onElement
and thePseudoElement
interface is removed. -
The
cascadedStyle
,defaultStyle
,rawComputedStyle
andusedStyle
IDL attributes onElement
are removed. -
The
cssText
IDL attribute’s setter onCSSRule
is changed to do nothing. -
IDL attributes of the form
webkitFoo
(with lowercasew
) onCSSStyleDeclaration
are added. -
CSSNamespaceRule
is changed back to readonly. -
Handling of
@charset
ininsertRule()
is removed. -
CSSCharsetRule
is removed again. -
Serialization of identifiers and strings is changed.
-
Serialization of selectors now supports combinators ">>" and "||" and the "i" flag in attribute selectors.
-
Serialization of:lang() is changed.
-
setProperty()
onCSSStyleDeclaration
is changed.
11.3.Changes From 12 July 2011 To 5 December 2013
- Cross-origin stylesheets are not allowed to be read or changed.
CSSCharsetRule
is re-introduced.CSSGroupingRule
andCSSMarginRule
are introduced.CSSNamespaceRule
is now mutable.- Parseandserializea CSS declaration block is now defined.
- Shorthands are now supported in
setProperty()
,getPropertyValue()
,et al. setPropertyValue
andsetPropertyPriority
are added toCSSStyleDeclaration
.- The
style
andmedia
attributes of various interfaces are annotated with the[PutForwards]
WebIDL extended attribute. - The
pseudo()
method onElement
is introduced. - The
PseudoElement
interface is introduced. - The
cascadedStyle
,rawComputedStyle
andusedStyle
attributes onElement
andPseudoElement
are introduced. - TheCSS.escape()static method is introduced.
12.Security and Privacy Considerations
No new security or privacy considerations have been reported on this specification.
13.Acknowledgments
The editors would like to thank Alexey Feldgendler, Benjamin Poulain, Björn Höhrmann, Boris Zbasky, Brian Kardell, Chris Dumez, Christian Krebs, Daniel Glazman, David Baron, Domenic Denicola, Dominique Hazael-Massieux,fantasai, Hallvord R. M. Steen, Ian Hickson, John Daggett, Lachlan Hunt, Mike Sherov, Myles C. Maxfield, Morten Stenshorne, Ms2ger, Nazım Can Altınova, Øyvind Stenhaug, Peter Sloetjes, Philip Jägenstedt, Philip Taylor, Richard Gibson, Robert O’Callahan, Simon Sapin, Sjoerd Visscher, Sylvain Galineau, Tarquin Wilton-Jones, Xidorn Quan, 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.