CSS calculate the specificity

How do you calculate the specificity of a particular selector? It’s fairly straightforward if you take into account that specificity will be represented as four numbers separated by commas, like: 1, 1, 1, 1 or 0, 2, 0, 1

  1. The first digit (a) is always zero, unless there is a style attribute applied to that element within the markup itself
  2. The second digit (b) is the sum of the number of IDs in that selector
  3. The third digit (c) is the sum of other attribute selectors and pseudo-classes in that selector. Classes (.example) and attribute selectors (eg. li[id=red]) are included here.
  4. The fourth digit (d) counts the elements (like table, p, div, etc.) and pseudo-elements (like :first-line)
  5. The universal selector (*) has a specificity of zero
  6. If two selectors have the same specificity, the one that comes last on the stylesheet will be applied

Let’s take a look at a few examples, to make it easier to understand:

  • #sidebar h2 — 0, 1, 0, 1
  • h2.title — 0, 0, 1, 1
  • h2 + p — 0, 0, 0, 2
  • #sidebar p:first-line — 0, 1, 0, 2

From the following selectors, the first one is the one who will be applied to the element, because it has the higher specificity:

  • #sidebar p#first { color: red; } — 0, 2, 0, 1
  • #sidebar p:first-line { color: blue; } — 0, 1, 0, 2

 

#sidebar p:first-line the priority will be higher than #sidebar p#first 

Reference: http://coding.smashingmagazine.com/2009/08/17/taming-advanced-css-selectors/

沒有留言:

張貼留言