CSS :visited property
The :visited
pseudo-class in CSS is used to style links that the user has already visited. It applies styles to <a>
elements (anchors) that point to a URL the user has previously accessed. This helps users identify which links they've already clicked, providing visual feedback and improving navigation.
Syntax
a:visited {
/* styles */
}
a
: The selector targets anchor (<a>
) elements.:visited
: The pseudo-class applies styles to links that the user has visited.
How It Works
Basic Usage:
- You can style visited links differently from unvisited links to provide a visual cue of their status.
a:link { color: blue; } a:visited { color: purple; }
- In this example, all unvisited links are blue, and visited links are purple.
Order of Pseudo-Classes:
- The
:visited
pseudo-class must be used after the:link
pseudo-class in your CSS. This ensures that styles for unvisited links are applied before styles for visited links.
a:link { color: blue; } a:visited { color: purple; }
- This order ensures that the
:visited
styles are only applied to links that have been visited.
- The
Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visited Example</title>
<style>
a:link {
color: blue;
text-decoration: none;
}
a:visited {
color: purple;
}
a:hover {
text-decoration: underline;
}
a:active {
color: red;
}
</style>
</head>
<body>
<a href="https://www.example.com">Visit Example</a>
<a href="https://www.example2.com">Visit Example 2</a>
</body>
</html>
Explanation:
a:link
:- Styles links that have not yet been visited. They appear blue and have no underline.
a:visited
:- Styles links that have been visited by the user. They appear purple.
a:hover
:- Styles links when the user hovers over them, adding an underline.
a:active
:- Styles links when they are being clicked, changing the color to red.
Important Points
Limited Styles:
- For security reasons, browsers limit the styles that can be applied to
:visited
links. You can only change certain properties, such ascolor
andtext-decoration
. Other properties likebackground-color
orborder
cannot be styled with:visited
.
- For security reasons, browsers limit the styles that can be applied to
Privacy Concerns:
- The restrictions on styles are partly to prevent websites from determining which URLs a user has visited, which could be used to infer private browsing habits.
Order of Pseudo-Classes:
- Ensure
:visited
is placed after:link
in your CSS. For example,a:link {}
should come beforea:visited {}
.
- Ensure
CSS and JavaScript:
- JavaScript cannot directly access the visited state of links due to privacy concerns. Styling is the primary method to indicate visited links.