One of our students was having a problem with review question 3.29 (page 131): “If there are two conflicting specifications in a document-level style sheet, which of the two has precedence?” This was covered in section 3.13, Conflict Resolution, but a good example or two might have made things clearer.
The gory details are explained at www.w3.org/TR/REC-CSS2/cascade.html. Here’s an extract from some courseware I wrote for a Internet training company:
Consider this code:
a {
color: blue;
font-family: sans-serif;
}
p a {
font-weight: bold;
font-family: serif;
}
.designer a {
text-decoration: none;
font-family: cursive;
}...
<p class="designer">Designed by <a href="mailto:tom@xyz.com">Tom Khumalo</a></p>
You can guess how you think the styles, especially for the font face, will be applied. But there is a definite methodical approach you can use to make the determination. The W3C’s specifications for CSS include specificity as a means of calculating the relative priority of styles. Specificity is written as a group of four numbers, such as (0,1,0,1). A selector’s specificity is calculated this way:
- If the declaration is from an inline style, that is, a style attribute associated with a particular instance of a tag, the specificity is (1,0,0,0).
- For each id attribute in the selector, add (0,1,0,0) to the specificity.
- For each class or pseudo-class attribute in the selector, add (0,0,1,0) to the specificity.
- For each element or pseudo-element in the selector, that is, for each tag named, add (0,0,0,1) to the specificity.
Looking at the specificity from left to right, larger numbers have greater precedence. Following these rules with the preceding example, we can calculate the specificity for each selector:
a: (0,0,0,1)
p a: (0,0,0,2)
.designer a: (0,0,1,1)
and the style for selector .designer a will take precedence.
What if we have two conflicting styles with the same calculated specificity? Then we fall back to the original rules concerning precedence: the last style encountered will prevail.