HTML and CSS Reference
In-Depth Information
Specificity is also cumulative in combined and descendant selectors. Each of the base selector types
carries a different weight in terms of specificity—a selector with two classes is more specific than a
selector with one class, a selector with one ID is more specific than a selector with two classes, and so on.
The specificity algorithm is carefully designed so that a large number of less specific selectors won't
outweigh a more specific selector. Even if you assembled a complex selector made up of hundreds of
element selectors, another rule with just one ID selector could still override it. Understanding specificity will
allow you to construct CSS rules that target elements with pinpoint accuracy.
For a more in-depth explanation of how specificity is calculated by web browsers, see
the W3C specification for CSS 2.1 ( )
at .
At this point you might be wondering what happens when two selectors target the same element and also
have the same specificity. For example:
.info h2 { color: purple; }
h2.title { color: orange; }
If an h2 element belonging to the “title” class is a descendant of another element in the “info” class, both of
these rules should apply to that h2 . How can the browser decide which rule to obey? Enter the cascade ,
the C in CSS.
Assuming selectors of equal specificity, style declarations are applied in the order in which they are
received, so later declarations override prior ones. This is true whether the declarations occur within the
same rule, in a separate rule later in the same style sheet, or in a separate style sheet that is downloaded
after a prior one. It's this aspect of CSS that gives the language its name: multiple style rules that cascade
over each other, adding up to the final presentation in the browser. In the earlier example, the rendered h2
element would be orange because the second rule overrides the first.
For another example, the following rule:
p {
color: black;
color: green;
contains two declarations, but rendered paragraphs will be green because that declaration comes later in
the cascade.
The sometimes-complex interplay between specificity and the cascade can make CSS challenging to work
with in the beginning, but once you understand the basic rules, it all becomes second nature. You'll learn
more about the cascade order in Chapter 3.
In some extremely rare cases where both specificity and the cascade may not be sufficient to apply your
desired value, the special keyword !important (complete with preceding exclamation point) can force a
Search WWH ::

Custom Search