If you have two (or more) conflicting CSS rules that point to the same element, there are some basic rules that a browser follows to determine which one is most specific and therefore wins out.
- Specificity determines, which CSS rule is applied by the browsers.
- Specificity is usually the reason why your CSS-rules don’t apply to some elements, although you think they should.
- Every selector has its place in the specificity hierarchy.
- If two selectors apply to the same element, the one with higher specificity wins.
- There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
- When selectors have an equal specificity value, the latest rule is the one that counts.
- When selectors have an unequal specificity value, the more specific rule is the one that counts.
- Rules with more specific selectors have a greater specificity.
- The last rule defined overrides any previous, conflicting rules.
- The embedded style sheet has a greater specificity than other rules.
- ID selectors have a higher specificity than attribute selectors.
- You should always try to use IDs to increase the specificity.
- A class selector beats any number of element selectors.
- The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.
- You can calculate CSS specificity with CSS Specificity Calculator.
You give every id selector (“#whatever”) a value of 100, every class selector (“.whatever”) a value of 10 and every HTML selector (“whatever”) a value of 1. Then you add them all up and hey presto, you have the specificity value.
p has a specificity of 1 (1 HTML selector)
div p has a specificity of 2 (2 HTML selectors; 1+1)
.sith has a specificity of 10 (1 class selector)
div p.sith has a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)
#sith has a specificity of 100 (1 id selector)
body #darkside .sith p has a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)
If all of these examples were used, div p.sith (with a specificity of 12) would win out over div p (with a specificity of 2) and body #darkside .sith p would win out over all of them, regardless of the order.
It’s easier to calculate the specificity using the first method. Let’s find out, how it actually is done.
1 * { } 0
2 li { } 1 (one element)
3 li:first-line { } 2 (one element, one pseudo-element)
4 ul li { } 2 (two elements)
5 ul ol+li { } 3 (three elements)
6 h1 + *[rel=up] { } 11 (one attribute, one element)
7 ul ol li.red { } 13 (one class, three elements)
8 li.red.level { } 21 (two classes, one element)
9 style=”” 1000 (one inline styling)
10 p { } 1 (one HTML selector)
11 div p { } 2 (two HTML selectors)
12 .sith 10 (one class selector)
13 div p.sith { } 12 (two HTML selectors and a class selector)
14 #sith 100 (one id selector)
15 body #darkside .sith p { } 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)