I'm reading Adam Freeman's "The Definitive Guide to HTML5", and have a question about CSS specificity. He gives the following example:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
a {
color: black;
}
a.myclass {
color: white;
background: grey;
}
</style>
</head>
<body>
<a href="http://apress.com">Visit the Apress website</a>
<p>I like <span>apples</span> and oranges.</p>
<a class="myclass" href="http://w3c.org">Visit the W3C website</a>
</body>
</html>
and states:
In this case, the selector a.myclass includes a class attribute, which means that the specificity of the style is 0-1-0 (0 id values + 1 other attributes + 0 element names). The other style has a specificity of 0-0-0 (that is, it contains no id values, other attributes or element names).
I would have expected that the "a.myclass" selector would have a specificity score of 0-1-1, because it includes both a class and an element. Similarly, I expected the "a" selector to have a score of 0-0-1. Entering these two selectors into this CSS Specificity Calculator does indeed produce the results I would expect. (except that this calculator includes inline styles in the score)
Can anyone explain Adam's comments, or should I report this as errata?
You are correct. a.myclass
selector has a specificity score of 0-1-1
. a
is a type selector and has to be counted with a score of 1.
Please check w3.org specificity examples:
* /* a=0 b=0 c=0 -> specificity = 0 */ LI /* a=0 b=0 c=1 -> specificity = 1 */ UL LI /* a=0 b=0 c=2 -> specificity = 2 */ UL OL+LI /* a=0 b=0 c=3 -> specificity = 3 */ H1 + *[REL=up] /* a=0 b=1 c=1 -> specificity = 11 */ UL OL LI.red /* a=0 b=1 c=3 -> specificity = 13 */ LI.red.level /* a=0 b=2 c=1 -> specificity = 21 */ #x34y /* a=1 b=0 c=0 -> specificity = 100 */ #s12:not(FOO) /* a=1 b=0 c=1 -> specificity = 101 */