Table of Contents
Introduction
While using CSS, one must have experienced CSS overriding issue; even the use of !important cannot solve the issue. CSS Specificity handles this issue.
It is an algorithm used to calculate the weight of a CSS Selector to determine which relevant rule from a list of CSS declarations will be applied to an element.
Note: Specificity is only applied when multiple CSS declarations are styling same element.How is Specificity Calculated?
Before getting into how specificity is calculated, let’s first try to understand about selector weight categories and their weights.
Selector Weight Categories
ID Column
Selects an element by ID, e.g., #test. For each ID selector, the weight value adds 1-0-0.
CLASS Column
Selects element(s) by classname, e.g., .faqs. Class column also includes pseudo-classes like :hover, :required, etc. and attribute selectors like input[type=”radio”]. For each of these, the weight value adds 0-1-0.
TYPE Column
Selects elements by type e.g., p, h1, table, etc. It also includes pseudo-elements like ::before, ::after, ::placeholder, and other double colon selectors. For each type selector, the weight value adds 0-0-1.
Except for the categories above, all other selectors like universal selector (*), :is(), :where() add no value to the weight.
Examples
Let’s look into some examples of CSS selectors and determine their weights.
<!-- Some HTML -->
<div id="para">
<p> Some text </p>
</div>
/* CSS */
#para {
color: blue;
}
/* Weight: 1-0-0 */
#para p {
color: red;
}
/* Weight: 1-0-1 */
Explanation:
In the example above, the weight of #para is 1-0-0 i.e., ID => 1, Class => 0 and Type => 0, while the weight of #para p is 1-0-1 i.e., ID => 1, Class => 0 and Type => 1. Here, the weight of ID is the same in both declarations but the type value of #para p is more than #para therefore, the paragraph inside #para will have color red and not blue.
Note: If the weight of all the declarations are the same, the last declaration will override all other declarations.
Learn More:
https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
Find More Tips and Tricks:
https://thinkshare.one/learn/tips-and-tricks/
If you have any confusion, feel free to leave a comment below or contact us.