CSS Specificity: Rules, Recursion, and Real-World Patterns
I have debugged countless CSS specificity issues over the years. Here is the mental model I use to solve them without resorting to!important. I remember spending three hours once trying to figure out why a button style was not applying. The selector looked correct. The property was spelled right. It turned out a deeply nested component library was loading its styles after mine, and the specificity difference was just enough to override my rule. That was the day I decided to truly understand specificity instead of slapping!important on everything. How Specificity Is Calculated Specificity is calculated as a four-part value representing four categories of selectors. The categories are, from highest to lowest: inline styles (the style attribute on an HTML element), ID selectors (#id), class selectors (.class), attribute selectors ([type]), and pseudo-classes (:hover), and finally element selectors (div, p) and pseudo-elements (::before). The browser compares these values from left to right. A selector with an ID always beats selectors with only classes and elements. A selector with more classes beats one with fewer. If two selectors have the same specificity, the one that appears later in the stylesheet wins. /* Specificity comparison */…