# What Is CSS Specificity?
CSS specificity is the algorithm by which browsers decide which property values to apply to a particular element. It is essentially a mathematical score that tells the browser "how specific" a rule is.If two rules have different specificity levels, the one with the higher weight will win, regardless of the order in which they were written. If both have the same weight, the last one declared in the source code wins.# How to Calculate CSS Specificity
Specificity is calculated based on three categories forming a three-column weight, often expressed as (A, B, C):- Column A (IDs): Counts the number of unique identifiers. Example:
#headercounts as 1 in column A. - Column B (Classes, Attributes and Pseudo-classes): Counts all classes (
.button), attributes ([type="text"]) and pseudo-classes (:hover). - Column C (Elements and Pseudo-elements): Counts all HTML elements (
div,h1) and pseudo-elements (::before).
# The Golden Rule: No Numeric Carry-Over
# The Problem With !important and BEM Architecture
The!important directive is an exception to specificity rules. When used, that declaration automatically overrides any other. It is considered bad practice because it destroys the natural cascade.To avoid specificity wars in large projects, methodologies like BEM advocate for using only single-depth class selectors, artificially keeping specificity flat at (0,1,0).