While writing CSS in VS Code, have you ever seen this and wondered what this selector specificity is?
If you don't know what selector specificity is and why it is important, then this article is for you.
Cascade, inheritance, and specificity are some of the important concepts every developer should know. You may know that if we select the same element and apply the same style to it, whatever will be declared at last will be applied, right?
Let's look at the example. Consider the following HTML.
<div>
<h1 class="heading">I am heading</h1>
</div>
Let's say we applied the following style to h1
h1 {
color: blue;
}
h1 {
color: red;
}
What will be the color of h1
?
As color: red
is declared later, it will be the color of h1
. Now, consider the following CSS.
.heading {
color: blue;
}
h1 {
color: red;
}
Now, what will be the color of h1
Why the color is blue? Because class selector is more specific than element selector.
Think about specificity as the number or weightage given to the selectors. Let's look at the specificity of each selector
Universal Selector *
Specificity - (0, 0, 0)
This means every other selector will override the properties defined inside this selector.
Element Selector
Specificity - (0, 0, 1)
So, any element selector, for example, h1
and button
, has specificity (0, 0, 1). Look at the second image above.
What if I have a descendant selector with two-element selectors.
div h1 {
/* your style here */
}
The value will be added, which mean the specificity of the above selector will be (0, 0, 2)
Class / Attribute / Pseudo-Class Selector
Specificity - (0, 1, 0)
.my-class {
/* your style here */
}
The above selector has specificity (0, 1, 0)
Now, consider the following code.
[class=text] p:hover {
/* your style here */
}
What will be the specificity of this selector?
We have an attribute selector (0, 1, 0), an element selector (0, 0, 1), and pseudo-class selectors (0, 1, 0). So the specificity will be (0, 2, 1)
ID Selectors
Specificity - (1, 0, 0)
#myDiv {
/* your style here */
}
Specificity of the above selector will be (1, 0, 0)
#myDiv #another-div a {
/* your style here */
}
We have two ID selectors (2, 0, 0), one element type selector (0, 0, 1), so the specificity of the selector will be (2, 0, 1)
Inline Style
Specificity - (1, 0, 0, 0)
The inline style will overwrite all your style rules in the CSS file.
!important property
Specificity - (1, 0, 0, 0, 0)
The !important
property has the highest specificity, use it carefully.
Also, note that universal selector and combinators such as +, ~, > don't increase specificity.
All right, we have come to the end of this article, I hope you enjoyed reading this article. Thank you for reading.
If you liked this article, you will love my tweets. I share useful things that will help you in your Web Development journey.