You can apply different element styles, depending on which elements they
are contained within. Consider the following HTML, for example:
This is a header
In the style sheet you can make the following declarations:
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 19
#main h2 { color:red; }
#sidebar h2 { color:blue; }
The header in main will be red, whereas the header in the sidebar will be blue??”despite
the fact that it is the same type of element being selected in each case.
Specificity
With the capability to declare styles with different types of selectors, a set of rules has been
defined to determine the importance of certain declarations over others. Specificity is an
important concept to grasp. As the sites or applications that you build get more complex, the
selectors required to properly style an element become even more complex.
Specificity is calculated by using four levels:
A. Count 1 if the selector is the style attribute. Style rules take precedence over everything
else.
B. Count the number of id attributes in the selector.
C. Count the number of other attributes (including classes and pseudoclasses) in the
selector.
D. Count the number of element names (including pseudoelement names) in the
selector.
Let??™s take a look at a few examples, each one increasing in specificity (see Table 2-1):
Table 2-1.
Pages:
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63