How to style link states: visited, hover, focus
Short answer
A link has five states, each with its own pseudo-class. Write them in exactly this order:
<style>
a:link { color: steelblue; }
a:visited { color: purple; }
a:hover { color: tomato; }
a:focus-visible { outline: 2px solid orange; outline-offset: 2px; }
a:active { color: crimson; }
</style>
<p><a href="https://example.com/new-page">A new page</a> · <a href="#">This page</a></p>:link— a link not visited yet;:visited— an already visited one;:hover— under the mouse pointer;:focus-visible— selected from the keyboard with Tab;:active— at the moment of pressing.
Why the order matters
All these selectors have the same specificity, so the one written lower wins. If :visited comes after :hover, visited links stop changing color on hover. The phrase "LoVe HAte" helps to remember the order: Link, Visited, Hover, Active.
Limits of :visited
For privacy, the browser lets visited links change colors only: color, background-color, border-color and similar. You cannot set the font size, a background image or display for :visited — otherwise any site could learn the browsing history.
Common mistake
Styles are set for a:hover and nothing for focus. With the mouse everything is visible, but when moving with Tab the selected link does not stand out. Add :focus-visible together with :hover, possibly in one rule: a:hover, a:focus-visible.
Functions used in this recipe
- :visited — Matches links the user has already opened; `:link` matches those not yet visited.
- :hover — Matches an element while the mouse pointer is over it.
- :focus-visible — Matches a focused element when the browser decides the focus should be visible — usually after keyboard navigation.
- :active — Matches an element while it is being pressed — between pressing and releasing the mouse button.
- <a> — A link to another page, a file or a place on the page.