Search code examples
htmlcsscss-selectorscss-specificity

Calculating the specificity of a selector(CSS)


I know that to calculate the specificity of a selector we use three numbers, where first number on the left is number of IDs, second number represents number of classes, pseudo-classes and attributes and third number represents number of elements.

I realize the following numbers are exaggerated … IDs are more specific than classes and classes are more specific than elements, but will the selector with specificity of 1.0.0 (thus selector with one ID) win over a selector with specificity of 0.222.0 ( selector with 222 classes/pseudo classes )?


Solution

  • Yep.

    Test:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title></title>
    <style type="text/css">
    #ID {color:red}
    .C1.C2.C3 ... .C220.C221.C222 {color:green}
    </style>
    </head>
    <body>
    <div id="ID" class="C1 C2 C3 ... C220 C221 C222">This is a test.</div>
    </body>
    </html>
    

    The text is red in recent Firefox, Chrome, IE, and Opera browsers.