timmfin
timmfin

Reputation: 2055

Why does the :link pseudo class break expected CSS specificity rules?

To my understanding, the CSS specificity rules indicate that a pseudo class has the same weight as a tag selector. So a selector like "div p a" would be more specific than "a:link".

But as the following test case demonstrates, that does not seem to be the case. Why is the link red?

<!DOCTYPE HTML>
<html>
<head>
    <title></title>
    <meta charset="UTF-8">

    <style type="text/css" media="screen">
        a:link { color: red; }
        div p a { color: green; }
        div.foobar p a { color: green; }
    </style>
</head>
<body>
    <div>
        <p>
          <a href="http://somecrazyurlwierdthing.com">A link... why is it red?</a>  
        </p>
    </div>

    <div class="foobar">
        <p>
          <a href="http://somecrazyurlwierdthing.com">But it turns green when you add a class selector.</a>  
        </p>
    </div>
</body>
</html>

Edited the example to include the "div.foobar p a" selector.

Upvotes: 6

Views: 745

Answers (3)

NickFitz
NickFitz

Reputation: 35051

The specification you link to states that a pseudo-class (:link in this case) has higher specificity than an element name. To be precise, using the a-b-c-d format, your three selectors come out as:

a-b-c-d
0 0 1 1
0 0 0 3
0 0 1 3

Your confusion possible comes from your use of the term "pseudo selector" which fails to recognise the distinction between pseudo-classes such as :link and pseudo-elements such as :first-line.

Upvotes: 6

Gab Royer
Gab Royer

Reputation: 9826

The thing is :link isn't a pseudo-element like :first-line, it's a pseudo-class and thus counts as a class for the specificity.

Source

Upvotes: 5

Rob Flaherty
Rob Flaherty

Reputation: 1055

Specificity for each:

a:link 0,0,1,1

div p a 0,0,0,3

a:link wins.

Upvotes: 2

Related Questions