HTML and CSS Reference
In-Depth Information
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?
At last, the name “Cascading Style Sheets” makes sense: CSS is based on a method of
causing styles to cascade together, which is made possible by combining inheritance
and specificity with a few rules. The cascade rules for CSS are simple enough:
1. Find all rules 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. 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, includ-
ing !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 to a given element. The later a declaration
appears in the style sheet or document, the more weight it is given. Declarations
that appear in an imported style sheet are considered to come before all declarations
within the style sheet that imports them.
To be perfectly clear about how this all works, let's consider some examples that illus-
trate the last three of the four cascade rules. (The first rule is kind of obvious, so we're
skipping right past it.)
Sorting by Weight and Origin
Under the second rule, if two rules apply to an element, and one is
marked !important , the important rule wins out:
p {color: gray !important;}
<p style="color: black;">Well, <em>hello</em> there!</p>
 
Search WWH ::




Custom Search