CSS Advanced - Specificity

Complete CSS Tutorial
First Step - Beginner CSSSecond Step - Intermediate CSSThird & Final Step - Advanced CSS
1. Applying CSS1. Class and ID Selectors1. Display
2. Selectors, Properties, and Values2. Grouping and Nesting2. Page Layout
3. Colors3. Pseudo Classes3. At-Rules
4. Text4. Shorthand Properties4. Pseudo Elements
5. Margins and Padding5. Background-images5. Specificity
6. Borders
7. Putting It All Together

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.

It may not seem like something that important, and in most cases you won't come across any conflicts at all, but the larger and more complex your CSS files become, or the more CSS files you start to juggle with, the greater likelihood there is of conflicts turning up.
If the selectors are the same then the latest one will always take precedence. For example, if you had:


p { color: red; }
p { color: blue; }

Teach Yourself  by BH24 HTML Editor Tool!

p elements would be coloured blue because that rule came last.
However, you won't usually have identical selectors with conflicting declarations on purpose (because there's not much point). Conflicts quite legitimately come up, however, when you have nested selectors. In the following example:

div p { color: red; }
p { color: blue; }

Teach Yourself  by BH24 HTML Editor Tool!

It might seem that p elements within a div element would be coloured blue, seeing as a rule to colour p elements blue comes last, but they would actually be coloured red due to the specificity of the first selector. Basically, the more specific a selector, the more preference it will be given when it comes to conflicting styles.
CSS Tutorial by BH24

The actual specificity of a group of nested selectors takes some calculating. Basically, 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)
  • .tree has a specificity of 10 (1 class selector)
  • div p.tree has a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)
  • #baobab has a specificity of 100 (1 id selector)
  • body #content .alternative p has a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)
So if all of these examples were used, div p.tree (with a specificity of 12) would win out over div p (with a specificity of 2) and body #content .alternative p would win out over all of them, regardless of the order.