Rule Conflicts, Priority, and Precedence
The cascade allows well-written selectors to target any range of elements in the document, without respect to the level of the document tree in which that range of elements lies.
A close look at the selector examples presented so far reveals that
conflicts seem inevitable. A rule such as p { ...
} would apply to the preceding source example, but presumably so
would #bodycopy p { ... }. When there
is a conflict, which value gets applied?
Selector Priority
The types of selectors used in a rule dictate that rule’s priority. In ascending order of weight, they are:
User agent stylesheet selectors
User stylesheet selectors
The universal selector (
*)Elements and pseudoelements (e.g.,
first-letter)Classes, pseudoclasses (e.g.,
:hover), and attributes ([selected="selected"])idsValues of inline
styleattributes, as explained in The Awful Parts
Given any two rules, the one with the highest-priority selector
will automatically take precedence. In cases where two rules contain
selectors of equal priority, it then becomes necessary to count the
number of selectors in each rule—a rule with two id selectors takes priority over a rule with
one id selector and four (or
eighteen) class selectors, for
example.
When any two selectors claim identical priority and weight, it
then becomes necessary to consider the presence of any !important values that they contain, as well as their relative position in the source order of the styles applied to a document. The importance ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access