From Confusion to Clarity: Everything You Need to Know About CSS Specificity
CSS Specificity is a way the browser decides which CSS style to use on an element when there are multiple rules for the same element. It uses a four-part calculation (a, b, c, d) where the parts are determined like this:
a: Inline styles in HTML (
style:”….”;
).b: ID selectors (
#id
).c: Class selectors (
.class
), attributes ([attr]
), and pseudo-classes (:hover
).d: Number of type selectors (
div
,h1
) and pseudo-elements (::before
).
The rule with the highest priority wins. If the specificity values are the same, the CSS rules that come later will cascades the ones written earlier.
Specificity Calculation Examples
Type Selectors and Psuedo-elements:
Each type selector and pseudo-element adds to d. Examples of type selectors are
<div>, <p>
, and examples of pseudo-elements are::before, ::after
.Code Snippet:
<p class="example">Hello World</p>
p { color: blue; } /* Specificity: (0, 0, 0, 1) */
Class Selectors, Attributes, and Pseudo-classes:
Each class selector, attribute selector, or pseudo-class adds to c. Some examples are
.example
,:hover
, and:nth-child()
.Code Snippet:
<p class="example" id="unique">Hello World</p>
p { color: blue; } /* Specificity: (0, 0, 0, 1) */
.example { color: green; } /* Specificity: (0, 0, 1, 0) */
p.example { color: yellow; } /* Specificity: (0, 0, 1, 1) */
#unique { color: red; } /* Specificity: (0, 1, 0, 0) */
In the example above, the winning CSS rule is #unique
because it has the highest specificity value.
ID Selectors:
Id selectors adds to b. Some examples are
#id, #example
.Code Snippet:
<div id="main" class="content">Hello</div>
#main { font-size: 20px; } /* Specificity: (0, 1, 0, 0) */
.content { font-size: 16px; } /* Specificity: (0, 0, 1, 0) */
div { font-size: 12px; } /* Specificity: (0, 0, 0, 1) */
In the above example, the winning rule #main
because it has the highest priority.
Important Declarations (
!important
):The !important declaration cascades normal specificity. When there are competing
!important
rules, specificity decides which one wins.
<p class="example" id="unique">Hello World</p>
#unique { color: red !important; } /* Specificity: (0, 1, 0, 0) */
.example { color: blue !important; } /* Specificity: (0, 0, 1, 0) */
In the above example #unique
rules wins because of highes priority.
Inline Styles:
Inline styles are the most specific and always win unless overridden by
!important
.
<div id="main" style="color: purple;">Hello</div>
#main { color: red; } /* Specificity: (0, 1, 0, 0) */
In the above example Inline style (color:purple;
) will win because of higher specificity.
Conclusion:
By understanding how specificity is calculated, we can write cleaner code and create styles that are easier to maintain by using a clear method to resolve conflicts between multiple rules that target the same element.