CSS Specificity – Understand How CSS Rules Are Applied
CSS specificity determines which rules apply to an element when multiple rules could apply. It is a measure of the importance of a selector in the cascade process.
Specificity Rules
Specificity is calculated based on the types of selectors used in the rule. It is typically expressed as a four-part value, like (a, b, c, d):
a: Inline styles (e.g.,style="color: red;") get a value of 1 in this column.b: Counts the number of ID selectors in the selector.c: Counts the number of class selectors, attributes selectors, and pseudo-classes.d: Counts the number of element selectors and pseudo-elements.
Specificity Calculation
Here’s how specificity is calculated:
- Inline styles: Always have the highest specificity, represented by (1, 0, 0, 0).
- ID selectors: Each ID selector increases the
bcomponent by 1. - Class selectors, attributes, and pseudo-classes: Each increases the
ccomponent by 1. - Element selectors and pseudo-elements: Each increases the
dcomponent by 1.
Examples
- Inline Styles
<div style="color: red;"></div>
Specificity: (1, 0, 0, 0)
- ID Selector
#main { color: blue; }Specificity: (0, 1, 0, 0)
- Class Selector
.highlight { color: green; }Specificity: (0, 0, 1, 0)
- Element Selector
p { color: black; }specificity: (0, 0, 0, 1)
- Combination
#main .highlight p { color: orange; }Specificity: (0, 1, 1, 1)
Overriding Specificity
- More Specific Rule: A more specific rule will override a less specific rule.
p { color: black; } .highlight p { color: green; }The
colorofpinside.highlightwill be green because.highlight pis more specific. - Order of Appearance: If two selectors have the same specificity, the one that appears last in the CSS will take precedence.
p { color: black; } p { color: red; }The
colorofpwill be red because the second rule overrides the first one.
!important Rule: Adding !important to a declaration will override any other declarations, regardless of specificity.
p {
color: black !important;
}
.highlight p {
color: green;
}
- The
colorofpwill be black because!importanttakes precedence over normal specificity rules.
Practical Tips
- Use ID selectors sparingly to avoid overly specific rules that are hard to override.
- Use class selectors for reusable styles.
- Avoid using inline styles unless necessary as they have high specificity and can be difficult to override.
- Use
!importantsparingly as it makes debugging more challenging.
Understanding CSS specificity helps in writing efficient and manageable stylesheets, ensuring the right styles are applied to elements as intended.