O'Reilly logo

Cascading Style Sheets: The Definitive Guide, Second Edition by Eric A. Meyer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required