---
title: CSS Specificity
slug: experience/css-specificity
docTags: 
createdAt: 2025-03-17T13:03:29.736Z
---

CSS specificity is a set of rules that determine which styles are applied when multiple rules target the same element. It helps resolve conflicts between competing styles.

### How Specificity Works

Specificity is calculated based on the types of selectors used in a CSS rule. Each type has a weight, and the higher the specificity, the more precedence a rule has.

### Specificity Calculation

CSS assigns values based on selector types:

1. **Inline styles (style="")** → **Highest specificity**
   - Example: \<div style="color: red;">
   - Specificity: **1000**
2. **ID selectors (#id)** → **High specificity**
   - Example: #myId \{ color: blue; }
   - Specificity: **100**
3. **Class, Attribute, and Pseudo-class selectors (.class, \[attr], \:hover)** → **Medium specificity**
   - Examples:&#x20;
     - .myClass \{ color: green; }
     - \[type="text"] \{ color: black; }
     - \:hover \{ color: orange; }
   - Specificity: **10**
4. **Element and Pseudo-element selectors (div, h1, \::before)** → **Lowest specificity**
   - Examples:&#x20;
     - p \{ color: yellow; }
     - \::before \{ content: "Hello"; }
   - Specificity: **1**

### Specificity Examples

1. p \{ color: blue; } → Specificity **1**
2. .text \{ color: red; } → Specificity **10** (class selector is stronger than element selector)
3. \#main \{ color: green; } → Specificity **100** (ID is stronger than class)
4. style="color: black;" → Specificity **1000** (inline styles override everything else)

### Tiebreaker Rules

- If two selectors have the same specificity, the **latest** rule in the CSS file wins.
- !important overrides specificity but should be used sparingly.

### Best Practices

- Use **specificity wisely** to avoid unnecessary complexity.
- Prefer **classes** over IDs for reusability.
- Avoid overusing !important, as it makes debugging difficult.

