Junior
What do you know about the specificity of CSS selectors?
sobes.tech AI
Answer from AI
Specificity determines the priority of CSS rules when they conflict, and different styles are applied to the same element. It is calculated for each selector in a rule.
Specificity is a numerical value composed of four categories (A, B, C, D), written as 0,0,0,0. The higher the number, the higher the specificity.
Categories:
- A (inline style): Styles set by the
styleattribute in an HTML element. They have the highest specificity (e.g.,1,0,0,0). - B (ID): ID selectors (e.g.,
#my-id). Increase the second digit (e.g.,0,1,0,0). - C (Class, Attribute, Pseudo-class): Class selectors (e.g.,
.my-class), attribute selectors (e.g.,[type="text"]), pseudo-classes (e.g.,:hover,:first-child). Increase the third digit (e.g.,0,0,1,0). - D (Element, Pseudo-element): Tag selectors (e.g.,
div,p) and pseudo-elements (e.g.,::before,::after). Increase the fourth digit (e.g.,0,0,0,1).
Calculation examples:
p-0,0,0,1.my-class-0,0,1,0#my-id-0,1,0,0div p-0,0,0,2(sum of two tag specificities)#my-id .my-class-0,1,1,0(sum of ID and class specificity)div#my-id.my-class:hover-0,1,2,1(sum of tag, ID, class, and pseudo-class specificity)
Rules:
- Inline styles always have higher specificity than any other selector combination, except rules with the
!importantflag. - Rules with the
!importantflag have the highest priority, overriding even inline styles. Using!importantis not recommended due to debugging complexity. - When specificity is equal, the rule declared last in the CSS file takes precedence.
- The universal selector (
*) and:where()pseudo-class have a specificity of0,0,0,0and do not increase overall specificity.
/*
Specificity: 0,0,0,1
Will apply if no more specific rules exist
*/
p {
color: blue;
}
/*
Specificity: 0,0,1,0
Will override the rule for the p tag
*/
.text {
color: green;
}
/*
Specificity: 0,1,0,0
Will override the rule for the class .text
*/
#main-text {
color: red;
}
/*
Specificity: 1,0,0,0
Will be applied if the element has the attribute style="color: purple;"
*/
/* <p style="color: purple;">Text</p> */
/*
Very high specificity, will override all
Not recommended to use without extreme necessity
*/
.override-text {
color: black !important;
}