Understanding CSS specificity is crucial for any frontend developer, as it directly impacts how styles are applied to elements on a webpage. Specificity determines which CSS rules take precedence when multiple rules could apply to the same element. By mastering specificity, developers can avoid common pitfalls and ensure that their styles behave as intended, leading to fewer bugs and a more maintainable codebase.
Specificity is calculated based on the types of selectors used in a CSS rule. The more specific a selector, the higher its specificity score. This score is determined by a simple hierarchy:
| Selector Type | Specificity Value |
|---|---|
| Inline styles | 1,0,0,0 |
| ID selectors | 0,1,0,0 |
| Class selectors, attribute selectors, and pseudo-classes | 0,0,1,0 |
| Element selectors and pseudo-elements | 0,0,0,1 |
To illustrate how specificity works, consider the following CSS rules:
#header {
color: blue; /* Specificity: 0,1,0,0 */
}
.header {
color: red; /* Specificity: 0,0,1,0 */
}
h1 {
color: green; /* Specificity: 0,0,0,1 */
}
In this example, if you have an `
Let’s look at a practical example where understanding specificity can prevent bugs: