Specificity in CSS refers to the priority assigned to a declaration. Several key terms from the CSS specification are foundational:
- Rule Set: A combination of a selector followed by a declaration block.
- Declaration: A CSS property key-value pair, such as
color: red;. - Inline Style: Styles defined directly within a element's
styleattribute. - Internal Style: Styles defined within a
<style>block in the HTML. - External Style: Styles defined in a CSS file linked via a
<link>tag.
A hierarchy of declaration sources determines the broadest level of priority:
- Declarations marked with
!importanthave the highest priority. - Declarations with in a inline style are next.
- Declarations from internal or external stylesheets follow.
- Declarations obtained through inheritance have the lowest priority.
Internal and external styles share the same specificity calculation rules because they both apply styles via selectors.
When a single element matches multiple rule sets containing the same property, specificity values are compared. These values are derived from the selectors used:
| Selector Type | Weight | Example |
|---|---|---|
Type Selector (e.g., div) |
1 | div { } |
| Class Selector | 10 | .text { } |
| Pseudo-class Selector | 10 | :hover { } |
| Pseudo-element Selector | 10 | ::first-line { } |
| Attribute Selector | 10 | [type="text"] { } |
| ID Selector | 100 | #content { } |
| Inline Style Declaration | 1000 | style="..." |
| Inherited Declaration | 0 | N/A |
Note: Ten type selectors (weight: 10) have lower specificity than one class selector (weight: 10). The weight is based on the category, not the sum of individual selectors of the same type.
Consider this example:
<style>
#content .list li > a {
color: crimson;
}
.menu-item > a {
color: navy;
}
</style>
<div id="content">
<ul class="list">
<li class="menu-item">
<a>Link Text</a>
</li>
</ul>
</div>
To determine which color declaration wins, calculate the specificity for each selector chain:
#content .list li > a: ID (100) + Class (10) + Type (1) + Type (1) = 112.menu-item > a: Class (10) + Type (1) = 11
The declaration with specificity 112 prevails, so the link will be crimson. When competing declarations have identical specificity, the last one declared (source order) wins, a principle often called source order or cascade.