Topic 7 of 62
Specificity Rules
Overview
Specificity is the mathematical scoring system the Cascade uses to determine which CSS selector is more 'powerful'. When multiple conflicting selectors target the same element, the browser calculates their Specificity Score. The score is often conceptualized as a 3-digit number: IDs (1,0,0), Classes/Attributes (0,1,0), and Elements/Pseudo-elements (0,0,1). The selector with the highest score mathematically dominates.
Syntax
css
/*
Calculating Specificity: (IDs, Classes, Elements)
*/
/* Elements: 1 Tag = Score (0,0,1) */
button { background: gray; }
/* Classes: 1 Class = Score (0,1,0) */
/* Wins over the tag selector! */
.btn-submit { background: blue; }
/* Mixed: 1 Class + 1 Tag = Score (0,1,1) */
button.btn-submit { background: purple; }
/* IDs: 1 ID = Score (1,0,0) */
/* Absolutely crushes classes! */
#checkout-btn { background: green; }
/* Inline Styles in HTML = Score (1,0,0,0) */
/* <button style="background: red;"> - Crushes everything except !important */Common Pitfalls
- Assuming that 11 classes will beat 1 ID. Specificity does not carry over in base-10 math. A score of (0, 11, 0) will NEVER beat a score of (1, 0, 0). One ID is infinitely more powerful than any number of classes.
- Using ID selectors for styling components. Because their specificity is so astronomically high, if you ever need to override that style for a specific edge case later, you will be forced to use
!important, triggering a downward spiral of terrible code.
Interview Questions
Q:
Which of the following has higher specificity:
.header .nav .link or #main-link?A:
#main-link wins instantly. The first selector has 3 classes (0,3,0). The second selector has 1 ID (1,0,0). IDs completely trump classes.
Real-World Example
Writing high-specificity CSS to purposefully override an aggressive third-party library (like Bootstrap).
example
css
/* Bootstrap might have a highly specific rule like: */
.card .card-body a.btn { color: blue; } /* Score: (0, 3, 1) */
/* To override it without using !important, we just need to match or beat the score */
/* Adding the parent #app ID boosts our score to (1, 2, 1), guaranteeing victory! */
#app .card a.btn {
color: green;
}Check Your Knowledge
Test your understanding of Specificity Rules with these quick questions.