CSS Selector Specificity
CSS selector specificity determines which style will be applied when multiple selectors match the same element. The higher the specificity, the higher the style priority.
Specificity Formula
Specificity is calculated based on three categories
Important: The classical specificity counting system doesn't include !important, as it's a separate concept that overrides everything. Usually, we talk about three categories, but for completeness, !important can be mentioned as a special case:
- !important overrides all normal styles (separate from the specificity mechanism)
- Inline styles (embedded styles, e.g.,
style="color: red;") have the highest priority. - IDs give a weight of 100 points each.
- Classes, attributes, and pseudo-classes add 10 points each.
- Tags and pseudo-elements add 1 point each.
Specificity Examples
| Selector | Specificity | Explanation |
|---|---|---|
* | 0, 0, 0 | Universal selector, minimum weight. |
p | 0, 0, 1 | One tag (1 point). |
.class | 0, 1, 0 | One class (10 points). |
#id | 1, 0, 0 | One identifier (100 points). |
div.class | 0, 1, 1 | One tag (1) and one class (10). |
#id .class p | 1, 1, 1 | One ID (100), one class (10), one tag (1). |
style="color: red;" | Inline style | Maximum specificity. |
How Specificity Works
When styles from different selectors are applied to an element, the selector with greater specificity is used. If specificity is equal, the style that appears later in the code is applied (cascade rule).
Example
<div id="example" class="box">
Example text
</div>
/* Styles */
div { color: black; } /* 0, 0, 1 */
.box { color: blue; } /* 0, 1, 0 */
#example { color: red; } /* 1, 0, 0 */
/* Final style: text color will be red (#example). */
Tip:
Avoid excessive use of ID selectors. This makes code less flexible and complicates style overriding.