O'Reilly logo

HTML & CSS: The Good Parts by Ben Henick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

  1. User agent stylesheet selectors

  2. User stylesheet selectors

  3. The universal selector (*)

  4. Elements and pseudoelements (e.g., first-letter)

  5. Classes, pseudoclasses (e.g., :hover), and attributes ([selected="selected"])

  6. ids

  7. Values 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required