A:Hover and A:Visited — Order Matters in CSS

April 26, 2007

I spent far too much time last night on a problem that should have been obvious. It was a sign my CSS skillz are a bit rusty. Here’s how the problem presented itself: I was updating a website for a client and one of the desired results was that links would change color on mouseover using the a:hover selector. Nothing too crazy there. In fact, that code was already in the partially-complete stylesheet that I’d been given by the client.

As we wrapped up changes to the website, there was an odd issue with the styling of the links. We had two groups of links, and in each group, some of the :hover styling would be shown, and some wouldn’t. It was pretty random. Where things got even weirder, but I started to get a clue as to what was going on, was when the client reported they had the same problem on their end, but it was different links that were working or not. What would make it different between computers? A browser cache. And if it’s a browser cache, it might have something to do with :visited. Aha.

Order matters in CSS. After looking at the stylesheet it hit me: the definition for a:hover was above that for a:visited. As a result, the :visited styling kept getting applied and overrode the :hover styling. As soon as I rearranged the CSS, the formatting performed as desired.

Remember: in CSS, order matters.

[tags]css[/tags]

Leave a Comment

Previous post:

Next post: