CSS Cascading and Inheritance Level 4

W3C Candidate Recommendation Snapshot,

More details about this document
This version:
https://www.w3.org/TR/2022/CR-css-cascade-4-20220113/
Latest published version:
https://www.w3.org/TR/css-cascade-4/
Editor's Draft:
https://drafts.csswg.org/css-cascade-4/
Previous Versions:
History:
https://www.w3.org/standards/history/css-cascade-4
Implementation Report:
https://wpt.fyi/results/css/css-cascade
Feedback:
CSSWG Issues Repository
Editors:
Elika J. Etemad / fantasai(Invited Expert)
Tab Atkins Jr.(Google)
Suggest an Edit for this Spec:
GitHub Editor

Abstract

This CSS module describes how to collate style rules and assign values to all properties on all elements. By way of cascading and inheritance, values are propagated for all properties on all elements.

New in this level are therevertkeyword and<supports-condition>for the@importrule.

CSSis a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, etc.

Status of this document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in theW3C technical reports index at https://www.w3.org/TR/.

This document was published by theCSS Working Groupas aCandidate Recommendation Snapshotusing theRecommendation track. Publication as a Candidate Recommendation does not imply endorsement byW3Cand its Members. A Candidate Recommendation Snapshot has receivedwide review, is intended to gather implementation experience, and has commitments from Working Group members toroyalty-free licensingfor implementations. This document is intended to become a W3C Recommendation; it will remain a Candidate Recommendation at least untilto gather additional feedback.

Please send feedback byfiling issues in GitHub(preferred), including the spec code “css-cascade” in the title, like this: “[css-cascade]…summary of comment…”. All issues and comments arearchived. Alternately, feedback can be sent to the (archived) public mailing list[email protected].

This document is governed by the2 November 2021 W3C Process Document.

This document was produced by a group operating under theW3C Patent Policy. W3C maintains apublic list of any patent disclosuresmade in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes containsEssential Claim(s)must disclose the information in accordance withsection 6 of the W3C Patent Policy.

1.Introduction

CSS defines a finite set of parameters, calledproperties, that direct the rendering of a document. Eachpropertyhas a name (e.g.,color,font-size,orborder-style), a value space (e.g.,<color>,<length-percentage>,[ solid | dashed | dotted |… ]), and a defined behavior on the rendering of the document. Properties values are assigned to various parts of the document viaproperty declarations, which assign the property a value (e.g.red,12pt,dotted) for the associated element or box.

One of the fundamental design principles of CSS iscascading, which allows several style sheets to influence the presentation of a document. When different declarations try to set a value for the same element/property combination, the conflicts must somehow be resolved.

The opposite problem arises when no declarations try to set a the value for an element/property combination. In this case, a value is be found by way ofinheritanceor by looking at the property’sinitial value.

Thecascadinganddefaultingprocess takes a set of declarations as input, and outputs aspecified valuefor each property on each element.

The rules for finding the specified value for all properties on all elements in the document are described in this specification. The rules for finding the specified values in the page context and its margin boxes are described in[css-page-3].

1.1.Module Interactions

This section is normative.

This module replaces and extends the rules for assigning property values, cascading, and inheritance defined in[CSS2]chapter 6.

Other CSS modules may expand the definitions of some of the syntax and features defined here. For example, the Media Queries Level 4 specification, when combined with this module, expands the definition of the<media-query>value type as used in this specification.

For the purpose of this specification,text nodesare treated aselementchildren of their associated element, and possess the full set of properties; since they cannot be targeted by selectors all of their computed values are assigned bydefaulting.

2.Importing Style Sheets: the@importrule

The@importrule allows users to import style rules from other style sheets. If an@importrule refers to a valid stylesheet, user agents must treat the contents of the stylesheet as if they were written in place of the@importrule, with two exceptions:

For example, declarations in style rules from imported stylesheets interact with the cascade as if they were written literally into the stylesheet at the point of the@import.

Any@importrules must precede all other valid at-rules and style rules in a style sheet (ignoring@charset), or else the@importrule is invalid. The syntax of@importis:

@import [<url>|<string>]
[ supports( [<supports-condition>|<declaration>] ) ]?
<media-query-list>?;

where the<url>or<string>gives the URL of the style sheet to be imported, and the optional [<supports-condition>|<declaration>] and<media-query-list>(collectively, theimport conditions) state the conditions under which it applies.

The followingconditional@importruleonly loads the style sheet when the UAsupportsdisplay: flex, and only applies the style sheet on ahandhelddevice with amaximum viewport widthof 400px.
@import url( "narrow.css" ) supports(display: flex) handheld and (max-width: 400px);

If a<string>is provided, it must be interpreted as a<url>with the same value.

The following lines are equivalent in meaning and illustrate both@importsyntaxes (one withurl()and one with a bare string):
@import"mystyle.css";
@importurl("mystyle.css");

2.1.Conditional@importRules

Theimport conditionsallow the import to be media– or feature-support–dependent. In the absence of anyimport conditions,the import is unconditional. (Specifyingallfor the<media-query-list>has the same effect.) If theimport conditionsdo not match, the rules in the imported stylesheet do not apply, exactly as if the imported stylesheet were wrapped in@mediaand/or@supportsblocks with the given conditions.

The following rules illustrate how@importrules can be made media-dependent:
@importurl("fineprint.css")print;
@importurl("bluish.css")projection,tv;
@importurl("narrow.css")handheld and(max-width:400px);

User agents may therefore avoid fetching a conditional import as long as theimport conditionsdo not match. Additionally, if a<supports-condition>blocks the application of the imported style sheet, the UAmust notfetch the style sheet (unless it is loaded through some other link) andmustreturn null for the import rule’s CSSImportRule.styleSheet value (even if it is loaded through some other link).

The following rule illustrates how an author can provide fallback rules for legacy user agents without impacting network performance on newer user agents:
@importurl("fallback-layout.css")supports(not(display: flex));
@supports(display: flex){
...
}

Theimport conditionsare given by<media-query-list>,which is parsed and interpreted as amedia query list, and<supports-condition>,is parsed and interpreted as a [[supports query]]. If a<declaration>is given in place of a<supports-condition>, it must be interpreted as a<supports-decl>(i.e. the extra set of parentheses is implied) and treated as a<supports-condition>.

For example, the following two lines are equivalent:
@import"mystyle.css"supports(display: flex);
@import"mystyle.css"supports((display: flex));

The evaluation and full syntax of theimport conditionsare defined by theMedia Queries[MEDIAQ]andCSS Conditional Rules[CSS-CONDITIONAL-3]specifications.

2.2.Processing Stylesheet Imports

When the same style sheet is imported or linked to a document in multiple places, user agents must process (or act as though they do) each link as though the link were to an independent style sheet.

Note:This does not place any requirements on resource fetching, only how the style sheet is reflected in the CSSOM and used in specs such as this one. Assuming appropriate caching, it is perfectly appropriate for a UA to fetch a style sheet only once, even though it’s linked or imported multiple times.

Thecascade originof an imported style sheet is thecascade originof the style sheet that imported it.

Theenvironment encodingof an imported style sheet is the encoding of the style sheet that imported it.[css-syntax-3]

Tofetch an @import,given an@importrulerule:
  1. LetparentStylesheetberule’sparent CSS style sheet.[CSSOM]

  2. Ifrulehas a<supports-condition>, and that condition is not true, return.

  3. LetparsedUrlbe the result of theURL parsersteps withrule’s URL andparentStylesheet’slocation. If the algorithm returns an error, return.[CSSOM]

  4. Fetch a style resourcefromparsedUrl, with stylesheetparentStylesheet, destination "style", CORS mode "no-cors", and processResponse being the following steps givenresponseresponseand byte stream, null or failurebyteStream:

    1. IfmaybeByteStreamis not a byte stream, return.

    2. IfparentStylesheetis inquirks modeandresponseisCORS-same-origin, letcontent typebe"text/css". Otherwise, letcontent typebe the Content Type metadata ofresponse.

    3. Ifcontent typeis not"text/css", return.

    4. LetimportedStylesheetbe the result ofparsingbyteStramgivenparsedUrl.

    5. SetimportedStylesheet’sorigin-clean flagtoparentStylesheet’sorigin-clean flag.

    6. Ifresponseis notCORS-same-origin,unsetimportedStylesheet’sorigin-clean flag.

    7. Setrule’sstyleSheettoimportedStylesheet.

2.3.Content-Type of CSS Style Sheets

The processing of imported style sheets depends on the actual type of the linked resource:

If the linked resource’s type istext/css, it must be interpreted as a CSS style sheet. Otherwise, it must be interpreted as a network error.

3.Shorthand Properties

Some properties areshorthand properties, meaning that they allow authors to specify the values of several properties with a single property. Ashorthand propertysets all of itslonghand sub-properties, exactly as if expanded in place.

When values are omitted from ashorthandform, unless otherwise defined, each “missing”sub-propertyis assigned itsinitial value.

This means that ashorthandproperty declaration always setsallof itssub-properties, even those that are not explicitly set. Carelessly used, this might result in inadvertently resetting somesub-properties. Carefully used, ashorthandcan guarantee a “blank slate” by resettingsub-propertiesinadvertently cascaded from other sources.

For example, writingbackground: greenrather thanbackground-color: greenensures that the background color overrides any earlier declarations that might have set the background to an image withbackground-image.

For example, the CSS Level 1fontproperty is ashorthandproperty for settingfont-style,font-variant,font-weight,font-size,line-height,andfont-familyall at once. The multiple declarations of this example:
h1{
font-weight:bold;
font-size:12pt;
line-height:14pt;
font-family:Helvetica;
font-variant:normal;
font-style:normal;
}

can therefore be rewritten as

h1{font:bold12pt/14ptHelvetica}

As morefontsub-propertiesare introduced into CSS, the shorthand declaration resets those to their initial values as well.

In some cases, ashorthandmight have different syntax or special keywords that don’t directly correspond to values of itssub-properties. (In such cases, theshorthandwill explicitly define the expansion of its values.)

In other cases, a property might be areset-only sub-propertyof the shorthand: Like othersub-properties,it is reset to its initial value by the shorthand when unspecified, but the shorthand might not include syntax to set thesub-propertyto any of its other values.For example, thebordershorthand resetsborder-imageto its initial value ofnone, but has no syntax to set it to anything else.[css-backgrounds-3]

If ashorthandis specified as one of theCSS-wide keywords[css-values-3], it sets all of itssub-propertiesto that keyword, including any that arereset-only sub-properties. (Note that these keywords cannot be combined with other values in a single declaration, not even in a shorthand.)

Declaring ashorthandproperty to be!importantis equivalent to declaring all of itssub-propertiesto be!important.

3.1.Property Aliasing

Properties sometimes change names after being supported for a while, such as vendor-prefixed properties being standardized. The original name still needs to be supported for compatibility reasons, but the new name is preferred. To accomplish this, CSS defines two different ways of “aliasing” old syntax to new syntax.

legacy name aliases
When the old property’s value syntax is identical to that of the new property, the two names are aliased with an operation on par with case-mapping: at parse time, the old property is converted into the new property. This conversion also applies in the CSSOM, both for string arguments and property accessors: requests for the old property name transparently transfer to the new property name instead.
For example, ifold-nameis alegacy name aliasfornew-name,getComputedStyle(el).oldNamewill return the computed style of thenewNameproperty, andel.style.setPropertyValue("old-name","value")will set thenew-nameproperty to"value".
legacy shorthands
When the old property has a distinct syntax from the new property, the two names are aliased using theshorthandmechanism. These shorthands are defined to belegacy shorthands, and their use isdeprecated. They otherwise behave exactly as regular shorthands, except that the CSSOM will not use them when serializing declarations.[CSSOM]
For example, thepage-break-*properties arelegacy shorthandsfor thebreak-*properties (seeCSS Fragmentation 3§ 3.4 Page Break Aliases: the page-break-before, page-break-after, and page-break-inside properties).

Settingpage-break-before: alwaysexpands tobreak-before: pageat parse time, like other shorthands do. Similarly, ifbreak-before: pageis set, callinggetComputedStyle(el).pageBreakBeforewill return"always". However, when serializing a style block (seeCSSOM 1§ 6.7.2 Serializing CSS Values), thepage-break-beforeproperty will never be chosen as the shorthand to serialize to, regardless of whether it orbreak-beforewas specified; instead,break-beforewill always be chosen.

3.2.Resetting All Properties: theallproperty

Name: all
Value: initial|inherit|unset|revert
Initial: see individual properties
Applies to: see individual properties
Inherited: see individual properties
Percentages: see individual properties
Computed value: see individual properties
Animation type: see individual properties
Canonical order: per grammar

Theallproperty is ashorthandthat resetsallCSS properties exceptdirectionandunicode-bidi. It only accepts theCSS-wide keywords. It does not resetcustom properties[css-variables-1].

Note:The excepted CSS propertiesdirectionandunicode-bidiare actually markup-level features, andshould not be set in the author’s style sheet. (They exist as CSS properties only to style document languages not supported by the UA.) Authors should use the appropriate markup, such as HTML’sdirattribute, instead.[css-writing-modes-3]

For example, if an author specifiesall: initialon an element, it will block all inheritance and reset all properties, as if no rules appeared in the author, user, or user-agent levels of the cascade.

This can be useful for the root element of a "widget" included in a page, which does not wish to inherit the styles of the outer page. Note, however, that any "default" style applied to that element (such as, e.g.display: blockfrom the UA style sheet on block elements such as<div>) will also be blown away.

4.Value Processing

Once a user agent has parsed a document and constructed a document tree, it must assign, to every element in theflat tree, and correspondingly to every box in the formatting structure, a value to every property that applies to the target media type.

The final value of a CSS property for a given element or box is the result of a multi-step calculation:

  1. First, all thedeclared valuesapplied to an element are collected, for each property on each element. There may be zero or manydeclared valuesapplied to the element.
  2. Cascading yields thecascaded value. There is at most onecascaded valueper property per element.
  3. Defaulting yields thespecified value. Every element has exactly onespecified valueper property.
  4. Resolving value dependencies yields thecomputed value. Every element has exactly onecomputed valueper property.
  5. Formatting the document yields theused value. An element only has aused valuefor a given property if that property applies to the element.
  6. Finally, the used value is transformed to theactual valuebased on constraints of the display environment. As with theused value,there may or may not be anactual valuefor a given property on an element.

Elements that are notconnectedor are not part of the document’sflattened element treedo not participate in CSS value processing, and do not havedeclared,cascaded,specified,computed,used,oractualvalues, even if they potentially have style declarations assigned to them (for example, by astyleattribute).

4.1.Declared Values

Each property declarationapplied to an elementcontributes adeclared valuefor that property associated with the element. SeeFiltering Declarationsfor details.

These values are then processed by thecascadeto choose a single “winning value”.

4.1.1.Value Aliasing

Some property values havelegacy value aliases: at parse time, the legacy syntax is converted into the new syntax, resulting in adeclared valuedifferent from the parsed input. These aliases are typically used for handling legacy compatibility requirements, such as convertingvendor-prefixedvalues to their standard equivalents.

4.2.Cascaded Values

Thecascaded valuerepresents the result ofthe cascade: it is thedeclared valuethat wins the cascade (is sorted first in theoutput of the cascade). If theoutput of the cascadeis an empty list, there is nocascaded value.

4.3.Specified Values

Thespecified valueis the value of a given property that the style sheet authors intended for that element. It is the result of putting thecascaded valuethrough thedefaultingprocesses, guaranteeing that aspecified valueexists for every property on every element.

In many cases, thespecified valueis thecascaded value. However, if there is nocascaded valueat all, thespecified valueisdefaulted. TheCSS-wide keywordsare handled specially when they are thecascaded valueof a property, setting thespecified valueas required by that keyword, see§ 7.3 Explicit Defaulting.

4.4.Computed Values

Thecomputed valueis the result of resolving thespecified valueas defined in the “Computed Value” line of the property definition table, generally absolutizing it in preparation forinheritance.

Note:Thecomputed valueis the value that is transferred from parent to child duringinheritance. For historical reasons, it is not necessarily the value returned by thegetComputedStyle()function, which sometimes returnsused values.[CSSOM]Furthermore, thecomputed valueis an abstract data representation: their definitions reflect that data representation, not how that data is serialized. For example, serialization rules often allow omitting certain values which are implied during parsing; but those values are nonetheless part of thecomputed value.

Aspecified valuecan be either absolute (i.e., not relative to another value, as inredor2mm) or relative (i.e., relative to another value, as inauto,2em). Computing a relative value generally absolutizes it:

See examples (f), (g) and (h) in thetable below.

Note:In general, thecomputed valueresolves thespecified valueas far as possible without laying out the document or performing other expensive or hard-to-parallelize operations, such as resolving network requests or retrieving values other than from the element and its parent.

Thecomputed valueexists even when the property does not apply. However, some properties may change how they determine thecomputed valuebased on whether the propertyapplies tothe element.

4.5.Used Values

Theused valueis the result of taking thecomputed valueand completing any remaining calculations to make it the absolute theoretical value used in the formatting of the document.

For example, a declaration ofwidth: autocan’t be resolved into a length without knowing the layout of the element’s ancestors, so thecomputed valueisauto, while theused valueis an absolute length, such as100px.[CSS2]

As another example, a<div>might have a computedbreak-beforevalue ofauto, but acquire a usedbreak-beforevalue ofpageby propagation from its first child.[css-break-3]

If a property does notapply tothis element or box type then it has noused valuefor that property.

For example, theflexproperty has noused valueon elements that aren’tflex items.

4.5.1.Applicable Properties

If a property does notapply toan element or box type—as noted in its “Applies to” line—this means it does not directly take effect on that type of box or element.

Note:A property that does not apply can still haveindirectformatting effects if its computed value affects the computation of other properties that do apply; and of course itscomputed value, which always exists, can still inherit to descendants and take effect on them.

Even thoughwriting-modeandtext-orientationdo not apply to table rows (they do not affect how the table row or its children are laid out), setting them on such boxes will still affect the calculation of font relative units such asch, and thus possibly any property that takes a<length>.
Settingtext-transformon an HTMLpelement (which isdisplay: blockby default) will have an effect, even thoughtext-transformonly applies toinline boxes, because the property inherits into the paragraph’s anonymousroot inline boxand applies to the text it contains.

Note:A property defined to apply to “all elements” applies to all elements anddisplay types, but not necessarily to allpseudo-elementtypes, since pseudo-elements often have their own specific rendering models or other restrictions. The::beforeand::afterpseudo-elements, however, are defined to generate boxes almost exactly like normal elements and are therefore defined accept all properties that apply to “all elements”. See[CSS-PSEUDO-4]for more information aboutpseudo-elements.

4.6.Actual Values

Aused valueis in principle ready to be used, but a user agent may not be able to make use of the value in a given environment.For example, a user agent may only be able to render borders with integer pixel widths and may therefore have to approximate theusedwidth. Also, the font size of an element may need adjustment based on the availability of fonts or the value of thefont-size-adjustproperty.Theactual valueis the used value after any such adjustments have been made.

Note:By probing the actual values of elements, much can be learned about how the document is laid out. However, not all information is recorded in the actual values. For example, the actual value of thepage-break-afterproperty does not reflect whether there is a page break or not after the element. Similarly, the actual value oforphansdoes not reflect how many orphan lines there is in a certain element. See examples (j) and (k) in thetable below.

4.7.Examples

Examples of CSS Value Computation
Property Winning declaration Cascaded value Specified value Computed value Used value Actual value
(a) text-align text-align: left left left left left left
(b) border-top-width,border-right-width,border-bottom-width,border-left-width border-width: inherit inherit 4.2px 4.2px 4.2px 4px
(c) width (none) (none) auto(initial value) auto 120px 120px
(d) list-style-position list-style-position: inherit inherit inside inside inside inside
(e) list-style-position list-style-position: initial initial outside(initial value) outside outside outside
(f) font-size font-size: 1.2em 1.2em 1.2em 14.1px 14.1px 14px
(g) width width: 80% 80% 80% 80% 354.2px 354px
(h) width width: auto auto auto auto 134px 134px
(i) height height: auto auto auto auto 176px 176px
(j) page-break-after (none) (none) auto(initial value) auto auto auto
(k) orphans orphans: 3 3 3 3 3 3

5.Filtering

In order to find thedeclared values, implementations must first identify all declarations that apply to each element. A declaration applies to an element if:

The values of the declarations that apply form, for each property on each element, a list ofdeclared values. The next section, thecascade, prioritizes these lists.

6.Cascading

Thecascadetakes an unordered list ofdeclared valuesfor a given property on a given element, sorts them by their declaration’s precedence as determined below, and outputs a singlecascaded value.

6.1.Cascade Sorting Order

The cascade sorts declarations according to the following criteria, in descending order of priority:

Origin and Importance
Theoriginof a declaration is based on where it comes from and itsimportanceis whether or not it is declared with!important(seebelow). The precedence of the variousoriginsis, in descending order:
  1. Transition declarations[css-transitions-1]
  2. Importantuser agentdeclarations
  3. Importantuserdeclarations
  4. Importantauthordeclarations
  5. Animation declarations[css-animations-1]
  6. Normalauthordeclarations
  7. Normaluserdeclarations
  8. Normaluser agentdeclarations

Declarations fromoriginsearlier in this list win over declarations from laterorigins.

Context
A document language can provide for blending declarations sourced from differentencapsulation contexts, such as the nestedtree contextsofshadow treesin the[DOM].

When comparing two declarations that are sourced from differentencapsulation contexts, then fornormalrules the declaration from the outer context wins, and forimportantrules the declaration from the inner context wins. For this purpose,[DOM]tree contextsare considered to be nested inshadow-including tree order.

Note:This effectively means thatnormaldeclarations belonging to anencapsulation contextcan set defaults that are easily overridden by the outer context, whileimportantdeclarations belonging to anencapsulation contextcan enforce requirements that cannot be overridden by the outer context.

Specificity
TheSelectors module[SELECT]describes how to compute the specificity of a selector. Each declaration has the same specificity as the style rule it appears in. For the purpose of this step, declarations that do not belong to a style rule (such as thecontents of a style attribute) are considered to have a specificity higher than any selector. The declaration with the highest specificity wins.
Order of Appearance
The last declaration in document order wins. For this purpose:
  • Declarations fromimported style sheetsare ordered as if their style sheets were substituted in place of the@importrule.
  • Declarations from style sheets independently linked by the originating document are treated as if they were concatenated in linking order, as determined by the host document language.
  • Declarations from style attributes are ordered according to the document order of the element the style attribute appears on, and are all placed after any style sheets.

Theoutput of the cascadeis a (potentially empty) sorted list ofdeclared valuesfor each property on each element.

6.2.Cascading Origins

Each style rule has acascade origin, which determines where it enters the cascade. CSS defines three coreorigins:

Author Origin
The author specifies style sheets for a source document according to the conventions of the document language. For instance, in HTML, style sheets may be included in the document or linked externally.
User Origin
The user may be able to specify style information for a particular document. For example, the user may specify a file that contains a style sheet or the user agent may provide an interface that generates a user style sheet (or behaves as if it did).
User-Agent Origin
Conforming user agents must apply a default style sheet (or behave as if they did). A user agent’s default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language (e.g., for visual browsers, the EM element in HTML is presented using an italic font). See e.g. theHTML user agent style sheet.[HTML]

Extensions to CSS define the following additionalorigins:

Animation Origin
CSS Animations[css-animations-1]generate “virtual” rules representing their effects when running.
Transition Origin
Like CSS Animations, CSS Transitions[css-transitions-1]generate “virtual” rules representing their effects when running.

6.3.Important Declarations: the!importantannotation

CSS attempts to create a balance of power between author and user style sheets. By default, rules in an author’s style sheet override those in a user’s style sheet, which override those in the user-agent’s default style sheet. To balance this, a declaration can be markedimportant, which increases its weight in the cascade and inverts the order of precedence.

A declaration isimportantif it has a!importantannotation as defined by[css-syntax-3], i.e. if the last two (non-whitespace, non-comment) tokens in its value are the delimiter token!followed by the identifier tokenimportant. All other declarations arenormal(non-important).

[hidden]{display:none!important;}

Animportantdeclaration takes precedence over anormaldeclaration. Author and user style sheets may containimportantdeclarations, withuser-originimportantdeclarations overridingauthor-originimportantdeclarations. This CSS feature improves accessibility of documents by giving users with special requirements (large fonts, color combinations, etc.) control over presentation.

Importantdeclarations from all origins take precedence over animations. This allows authors to override animated values in important cases. (Animated values normally override all other rules.)[css-animations-1]

User-agent style sheetsmay also containimportantdeclarations. These override allauthoranduserdeclarations.

The first rule in the user’s style sheet in the following example contains an!importantdeclaration, which overrides the corresponding declaration in the author’s style sheet. The declaration in the second rule will also win due to being marked!important. However, the third declaration in the user’s style sheet is not!importantand will therefore lose to the second rule in the author’s style sheet (which happens to set style on ashorthandproperty). Also, the third author rule will lose to the second author rule since the second declaration is!important. This shows that!importantdeclarations have a function also within author style sheets.
/* From the user’s style sheet */
p{text-indent:1em!important}
p{font-style:italic!important}
p{font-size:18pt}

/* From the author’s style sheet */
p{text-indent:1.5em!important}
p{font:normal12ptsans-serif!important}
p{font-size:24pt}
Property Winning value
text-indent 1em
font-style italic
font-size 12pt
font-family sans-serif

6.4.Precedence of Non-CSS Presentational Hints

The UA may choose to honor presentational hints in a source document’s markup, for example thebgcolorattribute orselement in[HTML]. All document language-based styling must be translated to corresponding CSS rules and enter the cascade as rules in either theUA-originor a special-purposeauthor presentational hint originbetween the regularuser originand theauthor origin. For the purpose ofcascadingthisauthor presentational hint originis treated as an independentorigin, but for the purpose of therevertkeyword it is considered part of theauthor origin.

A document language may define whether such a presentational hint enters thecascadeasUA-originorauthor-origin; if so, the UA must behave accordingly. For example,[SVG11]maps its presentation attributes into theauthor origin.

Note:Presentational hints entering thecascadeasUA-originrules can be overridden byauthor-originoruser-originstyles. Presentational hints entering the cascade asauthor presentational hint originrules can be overridden byauthor-originstyles, but not by non-importantuser-originstyles. Host languages should choose the appropriate origin for presentational hints with these considerations in mind.

7.Defaulting

When thecascadedoes not result in a value, thespecified valuemust be found some other way.Inherited propertiesdraw their defaults from their parent element throughinheritance; all other properties take theirinitial value. Authors can explicitly request inheritance or initialization via theinheritandinitialkeywords.

7.1.Initial Values

Each property has aninitial value, defined in the property’s definition table. If the property is not aninherited property, and thecascadedoes not result in a value, then thespecified valueof the property is itsinitial value.

7.2.Inheritance

Inheritancepropagates property values from parent elements to their children. Theinherited valueof a property on an element is thecomputed valueof the property on the element’s parent element. For the root element, which has no parent element, theinherited valueis theinitial valueof the property.

For a[DOM]tree with shadows, inheritance operates on theflattened element tree.This means that slotted elements inherit from theslotthey’re assigned to, rather than directly from theirlight treeparent.Pseudo-elementsinherit according to the fictional tag sequence described for eachpseudo-element.[CSS-PSEUDO-4]

Some properties areinherited properties, as defined in their property definition table. This means that, unless thecascaderesults in a value, the value will be determined byinheritance.

A property can also be explicitly inherited. See theinheritkeyword.

Note:Inheritance follows the document tree and is not intercepted byanonymous boxes, or otherwise affected by manipulations of the box tree.

7.3.Explicit Defaulting

Several CSS-wide property values are defined below; declaring a property to have these values explicitly specifies a particular defaulting behavior. As specified inCSS Values and Units[css-values-3], all CSS properties can accept these values.

7.3.1.Resetting a Property: theinitialkeyword

If thecascaded valueof a property is theinitialkeyword, the property’sspecified valueis itsinitial value.

7.3.2.Explicit Inheritance: theinheritkeyword

If thecascaded valueof a property is theinheritkeyword, the property’sspecifiedandcomputed valuesare theinherited value.

7.3.3.Erasing All Declarations: theunsetkeyword

If thecascaded valueof a property is theunsetkeyword, then if it is an inherited property, this is treated asinherit, and if it is not, this is treated asinitial. This keyword effectively erases alldeclared valuesoccurring earlier in thecascade, correctly inheriting or not as appropriate for the property (or all longhands of ashorthand).

7.3.4.Rolling Back Cascade Origins: therevertkeyword

If thecascaded valueof a property is therevertkeyword, the behavior depends on thecascade originto which the declaration belongs:

user-agent origin
Equivalent tounset.
user origin
Rolls back thecascaded valueto the user-agent level, so that thespecified valueis calculated as if noauthor-originoruser-originrules were specified for this property on this element.
author origin
Rolls back thecascaded valueto the user level, so that thespecified valueis calculated as if noauthor-originrules were specified for this property on this element. For the purpose ofrevert,this origin includes the Animationorigin.

8.Changes

8.1.Changes since the 15 Oct 2021 Working Draft

Non-trivial changes since the15 October 2021 Working Draft:

8.2.Changes Since the 28 August 2018 Candidate Recommendation

Non-trivial changes since the19 March 2021 Working Draftinclude:

Non-trivial changes since the18 August 2020 Working Draftinclude:

Non-trivial changes since the28 August 2018 Candidate Recommendationinclude:

8.3.Changes Since the 14 January 2016 Candidate Recommendation

Non-trivial changes since the14 January 2016 Working Draftinclude:

ADisposition of Commentsis available.

8.4.Changes Since the 21 April 2015 Working Draft

Changes since the21 April 2015 Working Draftinclude:

8.5.Additions Since Level 3

The following features have been added sinceLevel 3:

8.6.Additions Since Level 2

The following features have been added sinceLevel 2:

Acknowledgments

David Baron, Tantek Çelik, Simon Sapin, Noam Rosenthal, and Boris Zbarsky contributed to this specification.

Privacy and Security Considerations

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes.[RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text withclass= "example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text withclass= "note",like this:

Note, this is an informative note.

Advisements are normative sections styled to evoke special attention and are set apart from other normative text with<strong class= "advisement" >,like this:UAs MUST provide an accessible alternative.

Conformance classes

Conformance to this specification is defined for three conformance classes:

style sheet
ACSS style sheet.
renderer
AUAthat interprets the semantics of a style sheet and renders documents that use them.
authoring tool
AUAthat writes a style sheet.

A style sheet is conformant to this specification if all of its statements that use syntax defined in this module are valid according to the generic CSS grammar and the individual grammars of each feature defined in this module.

A renderer is conformant to this specification if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the features defined by this specification by parsing them correctly and rendering the document accordingly. However, the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to this specification if it writes style sheets that are syntactically correct according to the generic CSS grammar and the individual grammars of each feature in this module, and meet all other conformance requirements of style sheets as described in this module.

Partial implementations

So that authors can exploit the forward-compatible parsing rules to assign fallback values, CSS renderersmusttreat as invalid (andignore as appropriate) any at-rules, properties, property values, keywords, and other syntactic constructs for which they have no usable level of support. In particular, user agentsmust notselectively ignore unsupported component values and honor supported values in a single multi-value property declaration: if any value is considered invalid (as unsupported values must be), CSS requires that the entire declaration be ignored.

Implementations of Unstable and Proprietary Features

To avoid clashes with future stable CSS features, the CSSWG recommendsfollowing best practicesfor the implementation ofunstablefeatures andproprietary extensionsto CSS.

Non-experimental implementations

Once a specification reaches the Candidate Recommendation stage, non-experimental implementations are possible, and implementors should release an unprefixed implementation of any CR-level feature they can demonstrate to be correctly implemented according to spec.

To establish and maintain the interoperability of CSS across implementations, the CSS Working Group requests that non-experimental CSS renderers submit an implementation report (and, if necessary, the testcases used for that implementation report) to the W3C before releasing an unprefixed implementation of any CSS features. Testcases submitted to W3C are subject to review and correction by the CSS Working Group.

Further information on submitting testcases and implementation reports can be found from on the CSS Working Group’s website athttps://www.w3.org/Style/CSS/Test/. Questions should be directed to the[email protected]mailing list.

CR exit criteria

For this specification to be advanced to Proposed Recommendation, there must be at least two independent, interoperable implementations of each feature. Each feature may be implemented by a different set of products, there is no requirement that all features be implemented by a single product. For the purposes of this criterion, we define the following terms:

independent
each implementation must be developed by a different party and cannot share, reuse, or derive from code used by another qualifying implementation. Sections of code that have no bearing on the implementation of this specification are exempt from this requirement.
interoperable
passing the respective test case(s) in the official CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.
implementation
a user agent which:
  1. implements the specification.
  2. is available to the general public. The implementation may be a shipping product or other publicly available version (i.e., beta version, preview release, or "nightly build" ). Non-shipping product releases must have implemented the feature(s) for a period of at least one month in order to demonstrate stability.
  3. is not experimental (i.e., a version specifically designed to pass the test suite and is not intended for normal usage going forward).

The specification will remain Candidate Recommendation for at least six months.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSS-2021]
Tab Atkins Jr.; Elika Etemad; Florian Rivoal.CSS Snapshot 2021.31 December 2021. NOTE. URL:https://www.w3.org/TR/css-2021/
[CSS-ANIMATIONS-1]
Dean Jackson; et al.CSS Animations Level 1.11 October 2018. WD. URL:https://www.w3.org/TR/css-animations-1/
[CSS-BACKGROUNDS-3]
Bert Bos; Elika Etemad; Brad Kemper.CSS Backgrounds and Borders Module Level 3.26 July 2021. CR. URL:https://www.w3.org/TR/css-backgrounds-3/
[CSS-COLOR-4]
Tab Atkins Jr.; Chris Lilley; Lea Verou.CSS Color Module Level 4.15 December 2021. WD. URL:https://www.w3.org/TR/css-color-4/
[CSS-CONDITIONAL-3]
David Baron; Elika Etemad; Chris Lilley.CSS Conditional Rules Module Level 3.23 December 2021. CR. URL:https://www.w3.org/TR/css-conditional-3/
[CSS-CONDITIONAL-5]
David Baron; Elika Etemad; Chris Lilley.CSS Conditional Rules Module Level 5.21 December 2021. WD. URL:https://www.w3.org/TR/css-conditional-5/
[CSS-DISPLAY-3]
Tab Atkins Jr.; Elika Etemad.CSS Display Module Level 3.3 September 2021. CR. URL:https://www.w3.org/TR/css-display-3/
[CSS-FONTS-5]
Myles Maxfield; Chris Lilley.CSS Fonts Module Level 5.21 December 2021. WD. URL:https://www.w3.org/TR/css-fonts-5/
[CSS-PSEUDO-4]
Daniel Glazman; Elika Etemad; Alan Stearns.CSS Pseudo-Elements Module Level 4.31 December 2020. WD. URL:https://www.w3.org/TR/css-pseudo-4/
[CSS-SCOPING-1]
Tab Atkins Jr.; Elika Etemad.CSS Scoping Module Level 1.3 April 2014. WD. URL:https://www.w3.org/TR/css-scoping-1/
[CSS-SYNTAX-3]
Tab Atkins Jr.; Simon Sapin.CSS Syntax Module Level 3.24 December 2021. CR. URL:https://www.w3.org/TR/css-syntax-3/
[CSS-TRANSITIONS-1]
David Baron; et al.CSS Transitions.11 October 2018. WD. URL:https://www.w3.org/TR/css-transitions-1/
[CSS-VALUES-3]
Tab Atkins Jr.; Elika Etemad.CSS Values and Units Module Level 3.6 June 2019. CR. URL:https://www.w3.org/TR/css-values-3/
[CSS-VALUES-4]
Tab Atkins Jr.; Elika Etemad.CSS Values and Units Module Level 4.16 December 2021. WD. URL:https://www.w3.org/TR/css-values-4/
[CSS-VARIABLES-1]
Tab Atkins Jr..CSS Custom Properties for Cascading Variables Module Level 1.11 November 2021. CR. URL:https://www.w3.org/TR/css-variables-1/
[CSS-WRITING-MODES-3]
Elika Etemad; Koji Ishii.CSS Writing Modes Level 3.10 December 2019. REC. URL:https://www.w3.org/TR/css-writing-modes-3/
[CSS2]
Bert Bos; et al.Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification.7 June 2011. REC. URL:https://www.w3.org/TR/CSS21/
[CSSOM]
Daniel Glazman; Emilio Cobos Álvarez.CSS Object Model (CSSOM).26 August 2021. WD. URL:https://www.w3.org/TR/cssom-1/
[DOM]
Anne van Kesteren.DOM Standard.Living Standard. URL:https://dom.spec.whatwg.org/
[FETCH]
Anne van Kesteren.Fetch Standard.Living Standard. URL:https://fetch.spec.whatwg.org/
[HTML]
Anne van Kesteren; et al.HTML Standard.Living Standard. URL:https://html.spec.whatwg.org/multipage/
[MEDIAQ]
Florian Rivoal; Tab Atkins Jr..Media Queries Level 4.25 December 2021. CR. URL:https://www.w3.org/TR/mediaqueries-4/
[RFC2119]
S. Bradner.Key words for use in RFCs to Indicate Requirement Levels.March 1997. Best Current Practice. URL:https://datatracker.ietf.org/doc/html/rfc2119
[SELECT]
Tantek Çelik; et al.Selectors Level 3.6 November 2018. REC. URL:https://www.w3.org/TR/selectors-3/
[SELECTORS-4]
Elika Etemad; Tab Atkins Jr..Selectors Level 4.21 November 2018. WD. URL:https://www.w3.org/TR/selectors-4/
[URL]
Anne van Kesteren.URL Standard.Living Standard. URL:https://url.spec.whatwg.org/

Informative References

[CSS-ALIGN-3]
Elika Etemad; Tab Atkins Jr..CSS Box Alignment Module Level 3.24 December 2021. WD. URL:https://www.w3.org/TR/css-align-3/
[CSS-BREAK-3]
Rossen Atanassov; Elika Etemad.CSS Fragmentation Module Level 3.4 December 2018. CR. URL:https://www.w3.org/TR/css-break-3/
[CSS-BREAK-4]
Rossen Atanassov; Elika Etemad.CSS Fragmentation Module Level 4.18 December 2018. WD. URL:https://www.w3.org/TR/css-break-4/
[CSS-FLEXBOX-1]
Tab Atkins Jr.; et al.CSS Flexible Box Layout Module Level 1.19 November 2018. CR. URL:https://www.w3.org/TR/css-flexbox-1/
[CSS-FONTS-4]
John Daggett; Myles Maxfield; Chris Lilley.CSS Fonts Module Level 4.21 December 2021. WD. URL:https://www.w3.org/TR/css-fonts-4/
[CSS-INLINE-3]
Dave Cramer; Elika Etemad; Steve Zilles.CSS Inline Layout Module Level 3.27 August 2020. WD. URL:https://www.w3.org/TR/css-inline-3/
[CSS-LISTS-3]
Elika Etemad; Tab Atkins Jr..CSS Lists and Counters Module Level 3.17 November 2020. WD. URL:https://www.w3.org/TR/css-lists-3/
[CSS-PAGE-3]
Elika Etemad; Simon Sapin.CSS Paged Media Module Level 3.18 October 2018. WD. URL:https://www.w3.org/TR/css-page-3/
[CSS-SIZING-3]
Tab Atkins Jr.; Elika Etemad.CSS Box Sizing Module Level 3.17 December 2021. WD. URL:https://www.w3.org/TR/css-sizing-3/
[CSS-TEXT-3]
Elika Etemad; Koji Ishii; Florian Rivoal.CSS Text Module Level 3.22 April 2021. CR. URL:https://www.w3.org/TR/css-text-3/
[CSS-WRITING-MODES-4]
Elika Etemad; Koji Ishii.CSS Writing Modes Level 4.30 July 2019. CR. URL:https://www.w3.org/TR/css-writing-modes-4/
[SVG11]
Erik Dahlström; et al.Scalable Vector Graphics (SVG) 1.1 (Second Edition).16 August 2011. REC. URL:https://www.w3.org/TR/SVG11/

Property Index

Name Value Initial Applies to Inh. %ages Anim­ation type Canonical order Com­puted value
all initial | inherit | unset | revert see individual properties see individual properties see individual properties see individual properties see individual properties per grammar see individual properties