Calculating Specificity in Complex Selectors
You'll learn how to determine the specificity value of real-world selectors that combine multiple types of selectors together.
Now that you understand the point system (inline, IDs, classes, elements), it's time to practice with complex selectors that mix several parts. When a selector contains combinators and multiple pieces, you calculate specificity by adding up all the individual parts.
The Counting Method
Break down any selector into these categories:
- Inline styles: 1000 points (but not written in CSS files)
- IDs: 100 points each
- Classes, attributes, pseudo-classes: 10 points each
- Elements, pseudo-elements: 1 point each
Then add them all together!
Real-World Examples
Let's practice:
nav ul li → 0 IDs + 0 classes + 3 elements = 0-0-3 (3 points)
#sidebar .widget a:hover → 1 ID + 1 class + 1 pseudo-class + 1 element = 1-2-1 (121 points)
.menu li.active::before → 0 IDs + 2 classes + 1 element + 1 pseudo-element = 0-2-2 (22 points)
article > p[data-highlight] → 0 IDs + 1 attribute + 2 elements = 0-1-2 (12 points)
Think Like a Scorekeeper
Imagine you're tallying points in three separate columns: hundreds, tens, and ones. Count each selector piece, drop it in its correct column, then read the final score left-to-right. The selector with the highest score wins the cascade battle.
Key Takeaway: To calculate specificity in complex selectors, count all IDs (100s), classes/attributes/pseudo-classes (10s), and elements/pseudo-elements (1s), then add them together—the higher the total, the stronger the selector.