Strange results with an empty href and the :link p

2019-04-20 22:40发布

问题:

Here is some really simple markup and CSS:

a {
  color: red;
}
a:link {
  color: green;
}
<a href="#">one</a>
<a href="">two</a>
<a href>three</a>
<a>four</a>

FIDDLE

Now from the spec:

in HTML4, the link pseudo-classes apply to A elements with an "href" attribute.

So i'd expect the first 3 links to be green.

But no, the result is actually that only the first link that has a non-empty href is green.

So I used inspect element and I saw that the a:link selector actually overides the a selector in all of the first 3 cases, but for some reason only applies the style on the first case.

What is going on here?

One more thing, when I tested the various browsers I noticed that Chrome,Firefox and IE11 all produced the same results, except that in Firefox, when I reload the (same) code (in the fiddle just click 'Run') - all the first 3 elements suddenly turn green.

Any ideas?

回答1:

This would appear to be due to the way individual browsers chose to handle unvisited links. The W3 spec (http://www.w3.org/TR/CSS2/selector.html#link-pseudo-classes) states:

The :link pseudo-class applies for links that have not yet been visited.

Chrome (and Opera) see href="" and href as being the current url and thus deem them as visited. Firefox and IE treat href="" and href as unvisited until you actually click on them.

IE (unclicked):

Chrome (unclicked):

To support this logic, adding a fifth link with href="http://stackoverflow.com/questions/30371788/strange-results-with-an-empty-href-and-the-link-pseudo-class" (this page) will result in a red link in Chrome (similar to the href="" and href links) because it sees the page as visited.

a {
  color: red;
}
a:link {
  color: green;
}
<a href="#">one</a>
<a href="">two</a>
<a href>three</a>
<a>four</a>
<a href="http://stackoverflow.com/questions/30371788/strange-results-with-an-empty-href-and-the-link-pseudo-class">five</a>
<a href="unvisited">six</a>