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"]
)id
sValues of inline
style
attributes, 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 ...
Get HTML & CSS: The Good Parts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.