Finding Selector’s Specificity

Other than the style sheet precedence an order of precedence for the selectors in a style sheet is also present which depends on how specific the selector is. Formula is used to determine specificity as
  • Count 1 if the styles are applied from the (X)HTML style attribute, and 0 otherwise; this becomes variable a.
  • Count the number of ID attributes in the selector; the sum is variable b.
  • Count number of attributes, pseudo-classes, and class names in a selector; the sum is variable c.
  • Count the number of element names in the selector; this is variable d.
  • Ignore pseudo-elements.
Now take the four values and put them together in groups of four. In the following table I’ve demonstrated this, using commas to separate each value.

SELECTOR

SELECTOR TYPE

SPECIFICITY

*

Universal Selector

0,0,0,0, (a = 0, b = 0,c = 0, d = 0)

li

Element Name

0,0,0,1, (a = 0, b = 0,c = 0, d = 1)

ul li

Element Name

0,0,0,2, (a = 0, b = 0,c = 0, d = 2)

div h1 + p

Element Name

0,0,0,3, (a = 0, b = 0,c = 0, d = 3)

input[type=’text’]

Element Name + Attribute

0,0,1,1, (a = 0, b = 0, c = 1, d = 1)

.someclass

Class Name

0,0,1,0, (a = 0, b = 0,c = 1, d = 0)

div.someclass

Element Name + Class Name

0,0,1,1, (a = 0, b = 0,c = 1, d = 1)

div.someclass.someother

Element Name + Class Name +Class Name

0,0,2,1, (a = 0, b = 0,c = 2, d = 1)

#someid

ID Name

0,1,0,0, (a = 0, b = 1,c = 0, d = 0)

div#someid

Element Name + ID Name

0,1,0,1, (a = 0, b = 1,c = 0, d = 1)

style (attribute)

style (attribute)

1,0,0,0, (a = 1, b = 0,c = 0, d = 0)

Selector having the highest left-most number has the highest specificity. If two selectors have same specificity then they will be applied in the order in which they appear following example explains it
p.top {
background: none;
}
p.top {
background: #666;
}
Even though both ‘p.top’ have same specificity but here only the second applies as it is present below in the listing of styles and is applied ‘later’ hence it will display background: color #666.
If the style attribute of an HTML element is used, it is the most specific of any selector on the web page as it has a specificity of 1,0,0,0 hence it takes precedence over all other rules. It is not recommended to use style attributes as it removes the advantages of style cascading and the separation content and style.
Specificity is also explained by the figure asFinding Selector's Specificity
Share this post
[social_warfare]
Specificity hierarchy
Applying Font Formatting

Get industry recognized certification – Contact us

keyboard_arrow_up