The Cascade

Throughout this chapter, we’ve skirted one rather important issue: what happens when two rules of equal specificity apply to the same element? How does the browser resolve the conflict? For example, say you have the following rules:

h1 {color: red;}
h1 {color: blue;}

Which one wins? Both have a specificity of 0,0,0,1, so they have equal weight and should both apply. That simply can’t be the case because the element can’t be both red and blue. But which will it be?

Finally the name “Cascading Style Sheets” makes some sense. CSS is based on a method of causing styles to cascade together made possible by combining inheritance and specificity. The cascade rules for CSS2.1 are simple enough:

  1. Find all declarations that contain a selector that matches a given element.

  2. Sort by explicit weight all declarations applying to the element. Those rules marked !important are given higher weight than those that are not. Also sort by origin all declarations applying to a given element. There are three origins: author, reader, and user agent. Under normal circumstances, the author’s styles win out over the reader’s styles. !important reader styles are stronger than any other styles, including !important author styles. Both author and reader styles override the user agent’s default styles.

  3. Sort by specificity all declarations applying to a given element. Those elements with a higher specificity have more weight than those with lower specificity.

  4. Sort by order all declarations applying ...

Get Cascading Style Sheets: The Definitive Guide, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.