-
Hajipur, Bihar, 844101
CSS Specificity determines which CSS rule is applied when multiple rules target the same element. It defines the priority of a selector.
If multiple styles apply to the same element, the browser uses the rule with the highest specificity value.
Selector Type | Specificity Value |
---|---|
Universal (* ) |
0,0,0 |
Element (div , p ) |
0,0,1 |
Class (.class ) |
0,1,0 |
Attribute ([type] ) |
0,1,0 |
Pseudo-class (:hover ) |
0,1,0 |
ID (#id ) |
1,0,0 |
Inline styles | 1,0,0 (but higher priority) |
!important |
Overrides all (but avoid overuse) |
p {
color: blue; /* Specificity: 0,0,1 */
}
.text {
color: green; /* Specificity: 0,1,0 */
}
#main {
color: red; /* Specificity: 1,0,0 */
}
Final color: red due to higher specificity of
#main
.
Example:
div#main .text:hover {
color: orange;
}
Breakdown:
ID selector → 1
Class + Pseudo-class → 2
Element → 1
Specificity: 1,2,1
!important
Inline style:
<p style="color: purple;">Hello</p>
Inline styles have very high specificity: 1,0,0
Use of !important
:
p {
color: orange !important;
}
Overrides all other rules, even if specificity is lower.
If specificity is the same, the later rule in the CSS file wins.
p {
color: red;
}
p {
color: green;
}
Final color: green (last rule wins)
Q1. Set color using an element selector (h1
).
Q2. Override with a class selector (.title
).
Q3. Override again using an ID selector (#heading
).
Q4. Use an inline style to set background color.
Q5. Add !important
to a font-size rule.
Q6. Use both class and pseudo-class in a selector.
Q7. Add an attribute selector to style checkboxes.
Q8. Write a selector that combines element + ID + class.
Q9. Add multiple conflicting styles and determine which wins.
Q10. Use same specificity in two rules and reorder to test precedence.
Q1: Which selector has the highest specificity?
Q2: What does !important do?
Q3: What is the specificity of div.article .highlight?
Q4: Which style will be applied if all have the same specificity?
Q5: Which selector has specificity 1,0,0?
Q6: What is the specificity of input[type="text"]?
Q7: What is the specificity of an inline style?
Q8: Which of the following is the most specific?
Q9: If h1 and .title both style the same element, which wins?
Q10: Which selector has the lowest specificity?