CSS Specificity

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Abstract

When CSS doesn't do what you think it should, the major culprit here is Specificity. When there are more than one rule for a CSS element then the browser will follow some rules for determining the particular CSS property for an element. It often happens that properties of an element are set by different CSS selectors. So, Specificity is the way to determine which property value is most relevant for the element.

For example, it could happen that the color of the headline is set to yellow on h1 element, while at the same time the color of the same h1 element with the class="red" is set to red. Specificity helps prioritises what CSS property should be applied by the browser to the CSS element. In this case it is obvious that the color of the h1 element must become red but in many cases it is not that obvious. Therefore, specificity is required to know how the brwoser prioritises the CSS properties.

What is CSS Specificity?

CSS Specificity is the set of rules applied to the CSS selectors to determine which styles are applied to an element. Every selector has a specificity value. The more specific a CSS selector is, the larger it's the specificity value hence, it will be applied to an element.

CSS stands for Cascading Stylesheets, and in this context, cascading refers to the sequence in which CSS rules are applied to an element in order to style it. If two rules are applied to the same element, then, CSS specificity comes into picture to identify which rule should be applied to the element according to it's specificity value.

Note: When the specificity value of a selector between multiple rules is the same, the rule that is defined at the last is applied to that element.

How CSS Specificity works?

You know what is the specificity and how it's value is used to determine which style will be applied to the element on the web page. Now let's see an example to understand how specificity works.

Here, we want to assign color to the a tag. There are many ways to do that and some of them are:

As shown in the above CSS styling, all the rules apply the color property to the a tag and here the browser gets confused to apply the single color property to the a tag. To solve this issue, the value of specificity is calculated. The browser calculates the specificity value of all the selectors, and then it checks which selector has the highest value, and the rule which has higher specificity value wins i.e. that color will be applied to the a tag.

Here in the above example, the color of the <a> tag is red because the specificity value of the selector .container #main a is higher than the other selectors. You'll learn about how to calculate the specificity values of the selectors in the later section.

CSS Specificity Hierarchy

Specificity hierarchy was introduced by W3C(World Wide Web Consortium) and it is the hierarchy of order in which selectors are used. Every selector has some value and due to which the browser decides what rule should be allowed first and what later. For e.g. ID attribute selectors have higher specificity value than the class selectors, therefore styling present in the ID attribute will be applied to the element. You'll learn more about the order of selectors in later section.

Selectors and Rules are grouped into four categories and each of this group is assigned a special rank that allocates its value.

Rules - A CSS rule is a grouping of one or more CSS properties which are to be applied to one or more target HTML elements.

Each and every Selector belongs to only one group. Also, the Group 1 has the highest rank or value while the Group 4 has the lowest rank or value. Selectors with the highest value or rank are applied first and selectors with the lower rank have to wait. If the selectors have same value or rank, then the selector which comes last wins.

The groups according to W3C are:

  • Group 1: Inline Style - A style that is directly applied to an element using a style attribute. This category is highest in specificity value hierarchy. For e.g. <p style="color:green;">Lorem Ipsum</p>

  • Group 2: ID attributes - A style that is applied to an element with a given id. For e.g. #wrapper, #form-collect.

  • Group 3: class, pseudo-class, attributes - A style that applies to all elements with a given class value. e.g. .bg-yellow, .border-black. Includes pseudo-classes, e.g. :hover, :active, :focus. Also includes additional element attributes, e.g. [type="text"].

  • Group 4: elements, pseudo-elements - A style that applies to all elements with a given tag name (i.e. type).

    This category is the lowest in the specificity value hierarchy. These selectors are typically used for a webpage's baseline styling. This is especially useful for any style elements that will likely be applied to the majority of elements. For e.g. ul, section, div, ::before, ::after.

How to Calculate CSS Specificity?

To calculate the exact specificity value, you have to do some math. W3C provided a cheatsheet to calculate the specificity of the selector that is shown below.

Specificity can be calculated as a value. The selector with the highest value will prevail. If two properties happen to have the exact same specificity value, the one that appears last in the css code will prevail.

To calculate specificity:

  • A: Count if an element has an in-line style rule and apply the value 1,0,0,0 or A=1, B=0, C=0, D=0 or 1000.
  • B: Count the number of ID attributes in the selector and apply the value 0,1,0,0 for each or A=0, B=1, C=0, D=0 or 100.
  • C: Count the number of classes, pseudo-classes, and other attributes in the selector and apply the value 0,0,1,0 for each or A=0, B=0, C=1, D=0 or 10.
  • D: Count the number of element names and pseudo-elements in the selector and apply the value 0,0,0,1 for each or A=0, B=0, C=0, D=1 or 1.

In the example below:

The specificity will be 1(div) + 1(h1) + 1(h2) = 3


In the another example below,

the specificity will be

1 (li) + 10 (.green) + 10(.first) = 21

CSS Specificity Rules

  • Each selector gets points according to their groups, and the selector which has highest value wins.
  • The inline style receives the highest priority while the element selector has the lowest priority. For instance, inline styling is equivalent to 1000, which automatically wins.
  • Add 100 points/value for an ID selector.
  • For each class, attribute, or pseudo-class selector instance, add 10 points.
  • Add 1 point for each element/pseudo-elements instance.
  • The selector with the hightest points will be used as the element's style.

Scoring each CSS Selector type

  • Universal Selector (*):

    The universal selector is often used to reset the user agent styles. Universal Selectors has specificity 0 so any selector can override the universal selectors.

  • Inline Styles attribute:

    Inline styles are applied directly to an element using style attribute. The specificity of inline styles attribute is 1000. This overrides all the other selector values and dominate the styling wherever applied.

  • ID Selector:

    A style when it is applied thorugh id attribute. The specificity value for the ID selectors is 100.

  • Classes, attributes, and pseudo classes Selector:

    A style that applies to all elements with a given class value. The specificity value for the classes and pseudo classes is 10.

  • Elements, pseudo elements Selector:

    Element selectors let you style the selected element while pseudo elements allow you to style the part of specific element. The specificity value of the elements, pseudo elements is 1.

CSS Specificity in Context

You know about child element inheriting CSS properties from the parent element. Certain properties such as font, color, etc. when set to the parent element, is also applied to the child element i.e. child inherits the properties from the parent element. This is also called inheritance.

The specificity works in a different way in this context. When you target the elements directly, it will always take precedence over the inherited markup. Let's take an example to understand this better.

Here, in the context of the example above, any property applied to the option class will win against those inherited from the parent container i.e. div having the class contianer .

Visualizing CSS Specificity

  • For inline styles, the specificity is scored like this: Inline style specificity

  • For ID attributes, the specificity is scored like this: Specificity for ID attributes

  • For class, pseudo-classes and attributes the specificity is scored like this: Specificity for class, pseudo-classes, attributes

  • For elements and pseudo-elements, the specificity is scored like this: specificity score

How do you override specificity in CSS?

The !important declaration overrides every styling that is present in the stylesheet. Regardless of the selector, the style with !important declaration will be applied. The !important keyword is used in last attempt to win the CSS Specificity wars when all selectors fails.

In this example, all the other selectos are overriden by !important selector. It’s important to observe that this rule has nothing to do with specificity, it simply overrides the other selectors and it is considered as a bad practice.

Output of the above code snippet is

Exmaple of Important keyword

Conclusion

  • You learnt how the CSS styles are applied to the element if there are more than one rules are applied to the same sleector.
  • Although, CSS cpecificity is super simple but it can be very complex at times. So you should learn the basics so that you can avoid any unexpected results in your CSS files.
  • The universal selector (*) has the lowest specificity or it has the specificity value of (0,0,0,0).
  • You should avoid using !important keyword in your stylesheets. This will give you the strength to alter the CSS anytime but will cause harm in large code bases because you just can't override the every other CSS property.
  • The selector present inside the :not() pseudo class is counted while calculating the specificity. The :not() itself doesn't get counted.