Search code examples
htmlcsspseudo-class

The :link pseudo-class does match visited links


I was reading about CSS pseudo-classes and I came across the :link pseudo-class.

Everyone says that the :link pseudo-class matches link elements that have an "href" attribute and haven't been visited yet.

The first condition is true as I checked it out, but apparently the second condition (only matching unvisited links) is not the case (at least with Google Chrome) as you can see in the picture below:

Google Chrome Dev Tools

What's going on here?


Solution

  • It's a bit confusing but if you refer to the specification you will find:

    UAs may therefore treat all links as unvisited links, or implement other measures to preserve the user's privacy while rendering visited and unvisited links differently.

    This is what is happening here. The trick is to create some restrictions to avoid having a big difference between the styles of visited and unvisited links.

    Technically, all the styles you will apply to a:link will also apply to a:visited unless you override them inside a:visited and you are limited to the styles that you can apply inside :visited so you cannot override everything:

    You can style visited links, but there are limits to which styles you can use. Only the following styles can be applied to visited links:

    • color
    • background-color
    • border-color (and its sub-properties)
    • column-rule-color
    • outline-color
    • The color parts of the fill and stroke attributes

    In addition, even for the above styles, you won't be able to change the transparency between unvisited and visited links, as you otherwise would be able to using rgba(), hsla(), or the transparent keyword. ref

    Here is an example to illustrate:

    a:link {
      font-size:50px;
      border:2px solid red;
      color:black;
      padding:20px;
      box-shadow:5px 5px 0 blue;
      display:inline-block;
      margin:10px;
    }
    a:visited {
     color:red; /* this will work */
     border:5px dotted green; /* only the color will work */
     background:black; /* This will not work because we cannot change transparent to opaque value */
     
     /*All the below will not work*/
      padding:0;
      box-shadow:-5px -5px 0 purple;
      display:inline;
      margin:9584px;
      font-size:10px;
    }
    <a href="www.something.comg">not visited</a>
    
    <a href="#">visited</a>

    We are only allowed to slightly change the behavior from vistied to unvisited. Basically, we are only allowed to changed some colors.

    From this you can also conculde that a:link is almost1 the same as a. The difference is that the first one will only target links with href specified


    1: a:link or :link remain more specific than a

    :link {
     font-size:40px;
    }
    a {
     font-size:10px;
    }
    <a href="#">a link</a>