Understanding CSS Specificity

Ever wondered why your CSS styling is not being applied to your elements? To understand this, you need to have a basic understanding of CSS specificity.

What is Specificity?

Specificity in CSS refers to how browsers determine the importance, relevance, and “seniority” of CSS styles.

For you to understand CSS Specificity, you must understand CSS selectors. CSS Selectors-are that part of the CSS rule that finds or selects the HTML elements you want to style.

Specificity hierarchy

Every selector has its place in the specificity hierarchy. Before I list the hierarchy of CSS specificity, I want you to have this concept in your memory;

More Specific = Higher Priority

When a selector is more specific to an element, it has a higher priority

There are four distinct categories which define the specificity level of a given selector:

Inline styles: An inline style lives within your HTML document. It is attached directly to the element to be styled. E.g:

<h1 style="color: #fff;">

IDs (# selectors): An ID is an identifier for your page elements, such as #div.

Classes. Attributes and pseudo-classes: This group includes .classes, [attributes], and pseudo-classes such as :hover, :focus etc.

Elements and pseudo-elements: This is your div and span tags, and also the: before and: after used with them.

Specificity Calculation

There is a way of calculating the CSS specificity of a selector to see whether it will take precedence over another. The highest calculated sum takes precedence and thus will be applied to the element.

How to measure specificity

You can measure by following this calculation:

  • Start at zero.
  • Add 1000 for each inline-style.
  • Add 100 for each ID.
  • Add 10 for each attribute, class, and pseudo-class.
  • Add 1 for each tag or pseudo-element.
body #content .block img:hover

The specificity value would be 122.

  • 1 for body element.
  • 100 for #content ID.
  • 10 for .block class.
  • 1 for img element.
  • 10 for :hover pseudo-class.

Another way to indicate specificity is in a number form, often with commas between each number. For example "1,2,2" indicates a specificity of one ID, two classes, and two tags. IDs having the highest priority are listed first, followed by classes then tags.

The selector #page-header #page-title has two IDs, no classes, and no tags. We can say this has a specificity of 2,0,0. The selector ul li with two tags but no IDs or classes, has a specificity of 0,0,2.