Calculate CSS Specificity Value

Selector specificity is a process used to determine which rule will be applied in CSS when several rules specified to a element.

ul#mymenu li {
    color: red;
}
 
li.highlight {
    color: blue;
}
<ul id="mymenu">
    <li>item1</li>
    <li class="highlight">item2</li>
</ul>

What color will be applied to item2, red or blue? Answer is red. Because - ul#mymenu li has higher specificity value then li.highlight.

Selectors:

ID Class Pseudo-class Attribute Element Pseudo-element
#msgContainer .message a:visited p[title] div, p, span p:first-line, a:link:after

Priority Table:

Inline Style IDs Classes, Attributes, and Pseudo-classes Element Types and Pseudo-elements
Priority 1 2 3 4

Sample calculations:

div#msgContainer div#warning p.message {
    color: red;
}
Inline Style IDs Classes, Attributes, and Pseudo-classes Element Types and Pseudo-elements
Specificity Value 0 2 1 3
Counted elements no inline style #msgContainer, #warning .message div, div, p

Example:

Selectors Inline Style IDs Classes, Attributes, and Pseudo-classes Element Types and Pseudo-elements
body #content .data a:hover 0 1 2 (1 attribute, and 1 class) 2
<li style="color:red;"></li> 1 0 0 0

Notes:

  1. The !important is an automatic win. It overrides even inline styles. The way to override an !important by another !important rule declared later in the CSS and with equal or great specificity value otherwise.
  2. The universal selector(*, body) has a specificity of 0, 0, 0, 0.
  3. The last rule defined overrides any previous.
css
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License