learning-playground

Chapter 4: Specificity, Inheritance, and the Cascade

Specificity

Three weight categories, compared left-to-right: 0,0,0

1,0,0 always beats 0,500,500

Category Values:

Declarations and Specificity

Other Notes

Inheritance

Descendants only inherit with the exception of a few properties defined on <body> that are not defined on <html> (e.g., background, overflow)

The Cascade

Cascading Style Sheets

Rules

  1. Find all rules containing selector that matches a given element.
  2. Sort decls by explicit weight (normal or important).
  3. Sort decls by origin.
    • author > reader > user agent (normal)
    • user agent > reader > author (important)
  4. Sort decls by encapsulation context (e.g., shadow dom).
    • Allows encapsulated styles to override inherited styles from outside
  5. Sort decls by if they are element attached.
    • style = element attached
  6. Sort decls by cascade layer.
    • later the layer appears = higher precedence (normal weight)
    • no layer = implicit (default) = highest precedence (normal weight)
    • order reversed with important weight
  7. Sort decls by specificity.
  8. Sort decls by order of appearance.
    • imported stylesheets = before all styles in the sheet itself

Importance & Origin

Precedence order:

  1. Transition decls
  2. User Agent with important weight
  3. Reader with important weight
  4. Author with important weight
  5. Animation decls
  6. Author with normal weight
  7. User Agent with normal weight
  8. Reader with normal weight

Ex:

Cascade Layer

Introduced in 2021.

Ex:

Another good read: [Cascade Layers Guide CSS Tricks](/css-cascade-layers/#test-your-knowledge-which-style-wins)

Examples