Precedence of Selectors

Contact Us or call 1-877-932-8228
Precedence of Selectors

Precedence of Selectors

In the event that rules conflict:

  • The rule with the more specific selector takes precedence.
  • In the event that two selectors have the same specificity, the rule specified later in the document takes precedence.

Determining a Selector's Specificity

Note: This is important only for debugging; you'll almost never have to use it, except when you have conflicting styling declarations and can't figure out why one takes precedence over the other.

Imagine your selectors are stacked as follows with the ones on top having the highest specificity:Specificity

  1. Declarations in the style attribute have no selector and have the highest precedence.
  2. Selectors with id attributes (e.g., h1#foo {}) have the next highest precedence.
  3. Selectors with other attributes (e.g., h1.foo and a[target]) or pseudo-classes (e.g., a: hover) have the next highest precedence.
  4. Selectors with element names (e.g., h1) but no other attributes have the next highest precedence.
  5. The universal selector (*) has the lowest precedence.

To figure out the exact specificity, follow this process:

  1. Start with 0,0,0,0.
  2. If the declaration is found in the style attribute, change the first digit to 1, giving you 1,0,0,0. In this case, you have the highest possible specificity and can stop calculating.
  3. For each time the condition in level 2 is met, add 1 to the second digit.
    • For example, for ol#foo li#bar add 2 (1 for each id), giving you 0,2,0,0.
      • Note: we're not counting when the conditions in the other levels are met here, just the condition for level 2.
  4. For each time the condition in level 3 is met, add 1 to the third digit.
    • For example, for ol#foo li#bar a[target] add 1, giving you 0,2,1,0.
      • Note: here we're only counting when the conditions in level 2 and 3 are met.
  5. For each time the condition in level 4 is met, add 1 to the fourth digit.
    • For example, for ol#foo li#bar a[target] add 3 (1 for each element name), giving you 0,2,1,3.
      • Note: here we're counting when the conditions in level 2, 3, and 4 are met.

When comparing two selectors' specificity, start with the left-most numbers. If one has a higher number than the other, than it is more specific. If they are the same, look to the next number and so on.

Next