Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
timmfin Avatar asked Nov 26 '09 14:11

timmfin


People also ask

What affects CSS specificity?

As a special case for increasing specificity, you can duplicate weights from the CLASS or ID columns. Duplicating id, class, pseudo-class or attribute selectors within a compound selector will increase specificity when overriding very specific selectors over which you have no control.

What is doing link pseudo-class in CSS?

The :link CSS pseudo-class represents an element that has not yet been visited. It matches every unvisited <a> or <area> element that has an href attribute.

Which CSS selector has the highest specificity?

Rule 3: Inline CSS has the highest specificity. Inline CSS is the closest to the HTML element, so it is more specific and is therefore applied.

Why would you use a pseudo-class in CSS?

A pseudo-class is used to define a special state of an element. For example, it can be used to: Style an element when a user mouses over it. Style visited and unvisited links differently.


2 Answers

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.

like image 78
NickFitz Avatar answered Nov 20 '22 00:11

NickFitz


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

like image 44
Gab Royer Avatar answered Nov 20 '22 00:11

Gab Royer