How to Use :visited in CSS to Style Visited Links
Use the
:visited pseudo-class in CSS to style links that the user has already clicked. It works by targeting <a> elements with an href attribute that the browser remembers as visited. For example, a:visited { color: purple; } changes visited links to purple.Syntax
The :visited pseudo-class targets links that the user has already clicked on. It is used with anchor (<a>) elements that have an href attribute.
a:visited— selects all visited links.a:visited { property: value; }— applies styles to visited links.
Only certain CSS properties can be changed for visited links due to privacy restrictions.
css
a:visited {
color: purple;
text-decoration: underline;
}Example
This example shows normal links in blue and visited links in purple. When you click a link and return, the link color changes to purple to indicate it was visited.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Visited Link Example</title> <style> a { color: blue; text-decoration: none; } a:visited { color: purple; text-decoration: underline; } </style> </head> <body> <p>Visit <a href="https://example.com" target="_blank" rel="noopener">Example.com</a> and come back to see the link color change.</p> </body> </html>
Output
A webpage with a blue link labeled 'Example.com'. After clicking and returning, the link color changes to purple with underline.
Common Pitfalls
Many beginners expect to style visited links with any CSS property, but browsers limit this for privacy reasons. Only color, background-color, border-color, outline-color, and a few others can be changed.
Also, :visited only works on links with a valid href attribute. Links without href or with JavaScript handlers won't be styled.
css
/* Wrong: Trying to change layout or visibility */ a:visited { display: none; /* Won't work */ font-size: 20px; /* Won't work */ } /* Correct: Only color changes work */ a:visited { color: red; }
Quick Reference
| Property | Can be changed on :visited? |
|---|---|
| color | Yes |
| background-color | Yes |
| border-color | Yes |
| outline-color | Yes |
| text-decoration | No |
| font-size | No |
| display | No |
| visibility | No |
Key Takeaways
Use
:visited to style links the user has clicked on.Only certain CSS properties like color and background-color can change for visited links.
:visited works only on <a> elements with a valid href attribute.Browsers restrict styles on visited links to protect user privacy.
Test visited link styles by clicking links and returning to the page.