The Cascade

Through all this, we’ve skirted one rather important issue: what happens when there are two rules of equal specificity that apply to the same element? How does the browser resolve the conflict?

For example, let’s say we have the following rules:

H1 {color: red;}
H1 {color: blue;}

So which one wins? Both have a specificity of 1, so they have equal weight and should both apply. That simply can’t be the case, though, because the element can’t be both red and blue. It has to be one or the other. But which?

This is where the name “Cascading Style Sheets” finally makes some sense. CSS is based on a method of causing styles to cascade together—a method that is made possible by the rules of inheritance and specificity, as it happens. The cascade rules 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 given 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 author styles win out over important reader styles in CSS1, but in CSS2, !important reader styles are stronger than any other styles. Either author or reader styles will override user agent styles.

  3. Sort by specificity all declarations applying to a given element. Those elements with ...

Get Cascading Style Sheets: The Definitive Guide now with O’Reilly online learning.

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