CSS stands for Cascading Stylesheets. The cascade is the algorithm for solving conflicts where multiple CSS rules apply to an HTML element. It's the reason that the text of the button styled with the above CSS will be purple.
Understanding the cascade algorithm helps you understand how the browser resolves conflicts like this. The cascade algorithm has 4 distinct stages.
!important
rule typeTo calculate specificity, assign a value to each part of the selector:
Want to know more Selectors go there: CSS Selectors
Then, add up the values of all the parts in the selector.
Here is an example
<h1 id="title" class="h1">CodeWithHarry</h1>
Here, the specificity value will be 111 because ID has a specificity of 100, the class has a specificity of 10, and the h1 element has a specificity of 1.
In the case of a specificity tie, the rule that appears last in the CSS is applied.
The !important flag in CSS is used to give a particular style rule the highest level of importance, overriding any other competing styles. When you add !important to a CSS rule, it will take precedence over other rules affecting the same element, regardless of their specificity. For example, if you have:
p {
color: red !important;
}
p {
color: blue;
}
The text in the <p> element will be red, not blue, because the !important flag makes that rule more important.
an !important
at the end of a CSS value gets a specificity score of 10,000 points. This is the
highest specificity that one individual item can get.
However, it's generally best to use !important sparingly, as it can make debugging and maintaining your stylesheets more complicated. It can override styles in ways that are hard to trace, leading to unexpected results.
a.harryclass.rohan-class[href]:hover {
color: red;
}
To calculate the specificity value of the selector a.harryclass.rohan-class[href]:hover
, you can
break down its components:
Add up all these values:
1 (element) + 20 (classes) + 10 (attribute) + 10 (pseudo-class) = 41.
So, the specificity value of the selector a.harryclass.rohan-class[href]:hover
will be 41.