CSS Specificity is the system browsers use to determine which CSS rule takes priority when multiple selectors target the same HTML element. A selector with higher specificity generally overrides a selector with lower specificity, provided the declarations have the same cascade priority.
Understanding specificity helps you resolve styling conflicts and write more predictable CSS.
How CSS Specificity Works
CSS selectors have different specificity levels:
- ID selectors: Target elements using an ID, such as
#header. - Class selectors: Target classes, such as
.title, as well as attribute selectors and pseudo-classes. - Element selectors: Target HTML elements, such as
h1andp, and include pseudo-elements.
Inline styles have special precedence compared with ordinary stylesheet declarations. The full result also depends on the CSS Cascade.
CSS Specificity Example
Consider the following HTML and CSS:
<style>
p {
color: blue;
}
.message {
color: green;
}
#intro {
color: red;
}
</style>
<p id="intro" class="message">Welcome to Web4Learners!</p>
The paragraph appears red because the ID selector #intro has higher specificity than the class selector .message and the element selector p.
Understanding Specificity Scores
Specificity is commonly represented using four components:
Inline styles - IDs - Classes - Elements
For example:
| Selector | Specificity |
|---|---|
p | 0-0-0-1 |
.message | 0-0-1-0 |
#intro | 0-1-0-0 |
div p | 0-0-0-2 |
These values are a convenient comparison system, not ordinary decimal numbers. A higher-priority component outweighs lower-priority components.
Why Is CSS Specificity Important?
CSS Specificity helps you understand why one style overrides another. When two declarations have the same cascade priority, the selector with greater specificity generally wins. If their specificity is equal, the later declaration usually takes precedence.
You can also explore CSS Selectors to understand how different selectors target HTML elements, or learn how styles are applied in How CSS Works.