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:
Find all declarations that contain a selector that matches a given element.
Sort by explicit weight all declarations applying to the element. Those rules marked
!importantare 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.!importantreader styles are stronger than any other styles, including!importantauthor styles. Both author and reader styles override the user agent’s default styles.Sort by specificity all declarations applying to a given element. Those elements with a higher specificity have more weight than those with lower specificity.
Sort by order all declarations applying ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access