Sample code: http://jsfiddle.net/RuQNP/
<!DOCTYPE html>
<html>
<head>
<title>Foo</title>
<style type="text/css">
a:link, a:visited {
color: blue;
}
a:hover, a:active {
color: red;
}
.foo a:link, .foo a:visited {
color: green;
}
/* A possible fix */
/*
.foo a:hover, .foo a:active {
color: red;
}
*/
</style>
</head>
<body>
<div class="foo">
<a href="http://example.com/">Example</a>
</div>
</body>
</html>
What I was expecting:
The link would appear red on hover.
What I get:
The link appears green on hover.
Questions:
- Why does the
colordefined in.foo a:link, .foo a:visitedselector override the one ina:hover, a:active? What's going on? - I understand that I can fix it and get what I expect by uncommenting
the commented code. However, I want to know how can we correct the
.foo a:link, .foo a:visitedselector such that it does not override thecolordefined ina:hover, a:active?
If I understand http://www.w3.org/TR/CSS21/cascade.html#specificity properly (Thanks, BoltClock), this is the specificity table for the various selectors in the code.
a:link - 0 0 1 1
a:visited - 0 0 1 1
a:hover - 0 0 1 1
a:active - 0 0 1 1
.foo a:link - 0 0 2 1
.foo a:visited - 0 0 2 1
So, the style defined for .foo a:link overrides the style for a:hover when both link as well as hover pseudo-classes apply to an A element of class foo.
Similarly, the style defined for .foo a:visited overrides the style for a:hover when both visited as well as hover pseudo-classes apply to an A element of class foo.