When two selectors have same style, then one with higher specificity wins. In case they have same specificity, the one which come later, wins.
Specificity rules
Generate a number of the form a-b-c-d (in a number system with a large base). The value of a, b, c and d will be calculated using these rules:
a= | count 1 for css in style attribute (otherwise 0). When it is 1, then b=c=d=0 |
b= | count the number of ID selectors |
c= | count the number of class selectors, attributes selectors, and pseudo-classes |
d= | count the number of element names and pseudo-elements in the selector |
Few points to note:
- Universal selector can be ignored.
- Repeated occurrances of the same simple selector are allowed and do increase specificity.
Specificity examples
* {} /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */ li {} /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */ li::first-line {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul li {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul ol+li {} /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */ h1 + *[rel=up]{} /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */ ul ol li.red {} /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */ li.red.level {} /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */ #x34y {} /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */ style="color:red" /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */
Example css code
Specificity order in this example
attribute style > id > class > element
<style> div { width: 50px; height: 50px; background-color:orange; } .box { background-color:lightgreen; } #id1 { background-color:lightblue; } </style> <div> </div> <div class="box"> </div> <div id="id1" class="box"> </div> <div style="background-color:lightgray" class="box"> </div>