sajad torkamani

In a nutshell

SelectorScore
Element (e.g., p, div)1
Class (e.g., .app-header, .main-menu)10
ID (e.g., #main-button, #testimonials)100
Inline style (e.g., <div style="background: red;">)1000
!important (e.g., .div { color: red !important; } Infinity (more or less)

What if two selectors have the same specificity?

If two selectors have the same specificity the selector that’s parsed last in the CSS will take precedence (hence why CSS stands for Cascading Style Sheets). For example, given this stylesheet:

p.small-font {
  font-size: 14px;
}

p.large-font {
  font-size: 40px;
}

and this HTML:

<p class="large-font small-font">Hello there</p>

The <p> element will have a font size of 40px because the p.large-font style appeared after the p.small-font style in the CSS. The ordering of the class in the HTML is irrelevant. See this JSBin for live demo.

Example calculations

ElementSpecificity scoreCalculation
p11
p.test111 + 10
p#demo1011 + 100
<p style=”color: pink;”>10001000
#demo100100
.test1010
p.test1.test2211 + 10 + 10
#navbar p#demo201100 + 1 + 100
*00 (the universal selector is ignored)

Here’s a colorful illustration from specifishity.com:

CSS selector specificity

Sources

Tagged: CSS