HTML and CSS Reference
In-Depth Information
Obviously, only one of the two rules in each pair can win out, since the matched ele-
ments can be only one color or the other. How do you know which one will win?
The answer is found in the specificity of each selector. For every rule, the user agent
evaluates the specificity of the selector and attaches it to each declaration in the rule.
When an element has two or more conflicting property declarations, the one with the
highest specificity will win out.
This isn't the whole story in terms of conflict resolution. In fact, all style
conflict resolution (including specificity) is handled by the cascade,
which has its own section later in this chapter.
A selector's specificity is determined by the components of the selector itself. A spe-
cificity value can be expressed in four parts, like this: 0,0,0,0 . The actual specificity of
a selector is determined as follows:
• For every ID attribute value given in the selector, add 0,1,0,0 .
• For every class attribute value, attribute selection, or pseudo-class given in the
selector, add 0,0,1,0 .
• For every element and pseudo-element given in the selector, add 0,0,0,1 . CSS2
contradicted itself as to whether pseudo-elements had any specificity at all, but
CSS2.1 makes it clear that they do, and this is where they belong.
• Combinators and the universal selector do not contribute anything to the specif-
icity (more on these values later).
For example, the following rules' selectors result in the indicated specificities:
h1 {color: red;} /* specificity = 0,0,0,1 */
p em {color: purple;} /* specificity = 0,0,0,2 */
.grape {color: purple;} /* specificity = 0,0,1,0 */
*.bright {color: yellow;} /* specificity = 0,0,1,0 */
p.bright em.dark {color: maroon;} /* specificity = 0,0,2,2 */
#id216 {color: blue;} /* specificity = 0,1,0,0 */
div#sidebar *[href] {color: silver;} /* specificity = 0,1,1,1 */
Given a case where an em element is matched by both the second and fifth rules in the
example above, that element will be maroon because the fifth rule's specificity out-
weighs the second's.
As an exercise, let's return to the pairs of rules from earlier in the section and fill in the
h1 {color: red;} /* 0,0,0,1 */
body h1 {color: green;} /* 0,0,0,2 (winner)*/
h2.grape {color: purple;} /* 0,0,1,1 (winner) */
h2 {color: silver;} /* 0,0,0,1 */
Search WWH ::

Custom Search