A closer look at CSS cascading

Apr 17, 2021css-conceptscss

According to how CSS works, cascading is the key concept of CSS, which allows several style sheets to influence the presentation of a document.

The cascade algorithm takes an unordered list of declared values for a given property on a given element, sorts them by their declaration’s precedence as determined below, in descending order of priority, and outputs a single cascaded value.

  • Origin and importance
  • specificity
  • Order of appearance

When the cascade does not result in a value, the specified value must be found some other way. Inherited properties draw their defaults from their parent element through inheritance; all other properties take their initial value. Authors can explicitly request inheritance or initialization via the inherit and initial keywords.

Origin and Importance

Based on combination of declaration origins (user agent, user, author, transition, animation) and !important annotation. The precedence of the various origins is, in descending order:

1. Transition
2. User agent + `!important`
3. User + `!important`
4. Author + `!important`
5. Animation
6. Author
7. User
8. User agent
  • Author: 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: 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: 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).
  • Animation: CSS Animations generate virtual rules representing their effects when running.
  • Transition: Like CSS Animations, CSS Transitions generate virtual rules representing their effects when running.
  • !important: An important declaration takes precedence over a normal declaration. Author, user, and user-agent style sheets may contain important declarations.

Specificity

A weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector, highest specificity wins.

The resulting specificity is not a number but a tuple of numbers like (a,b,c). Read how to calculate CSS specificity for more details.

Order of Appearance

The last declaration in document wins in case of equal specificity.

  • Imported style sheets are substituted in place
  • Linked style sheets are concatenated in linking order
  • Inline styles are place after all style sheets