How CSS Specificity Is Calculated
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
Why Specificity Exists
When two CSS rules target the same element with conflicting values, the browser needs a way to decide which one wins. Specificity is that scoring system: it ranks selectors by how precisely they target an element, and the highest-scoring rule is applied.
The Specificity Scale
Specificity is commonly written as three numbers, often shown as (A, B, C):
| Category | Selectors counted | Weight |
|---|---|---|
| A | ID selectors (#id) | Highest |
| B | Classes, attribute selectors, pseudo-classes (.class, [type], :hover) | Middle |
| C | Type selectors and pseudo-elements (div, ::before) | Lowest |
Inline styles outrank all of these, and !important outranks inline styles - though both are usually best avoided since they make overriding a style later much harder.
Worked Examples
/* (0, 0, 1) - one type selector */
p { color: blue; }
/* (0, 1, 0) - one class selector: wins over the rule above */
.note { color: green; }
/* (0, 1, 1) - one class + one type: wins over a class alone */
p.note { color: purple; }
/* (1, 0, 0) - one ID: wins over everything above */
#warning { color: red; }When Specificity Is Equal
If two selectors have exactly the same specificity score, the rule that appears later in the stylesheet (or later in the cascade order) wins. This is why the order rules are written in a file can matter just as much as how specific they are.
Keeping Specificity Manageable
- Prefer classes over IDs for styling, saving IDs for unique landmarks or scripting hooks.
- Avoid deeply nested selectors that stack up specificity unnecessarily.
- Avoid
!importantexcept as a last resort - it breaks the normal cascade and is hard to override later.