CSS Selector Specificity

Shams NahidShams Nahid
2 min read

Overview

When an element in the browser has a conflict of styles, the browser uses a set of rules to determine which style should be rendered. This set of rules is defined as CSS Selector Specificity.

For instance, for an element, if we have the following DOM and CSS classes,

.myClass {
    color: yellow;
}
<div style="color: red;" class="myClass">My Text</div>

In this case, the color will be red, since the inline style has higher weight.

Calculation

Browser uses an array of four elements, where the previous index has higher priority. Consider these four elements a a, b, c and d.

[a, b, c, d]

A = Inline styles B = Number of selector IDs C = Classes, Pseudo Classes and Attributes D = Elements and Pseudo Elements

We calculate A, B, C, D as follows,

body.home #sidebar .menu li a:hover {
  color: gold;
}

Let’s break it down:

body → element → +1 to d
.home → class → +1 to c
#sidebarID → +1 to b
.menuclass → +1 to c
lielement → +1 to d
aelement → +1 to d
:hoverpseudo-class → +1 to c

Specificity: 0,1,3,3

Rules of Specificity

  • Higher specificity wins.

  • If specificity is the same, the last declared rule in the CSS wins.

  • Inline styles have the highest specificity (except !important).

  • !important can override normal specificity but should be used sparingly.

Best Practices

  • Write CSS with low specificity, so we can override it later

  • Avoid nested selectors and keep them shallow

0
Subscribe to my newsletter

Read articles from Shams Nahid directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shams Nahid
Shams Nahid

A lifelong learner. Love to travel. Listen to music.