In CSS, a pseudo-class is used to style elements when they are in specific states or conditions. It helps you apply different styles to elements based on their current situation.
Example:-
For instance, you can modify how an element looks when a user hovers over it or when they visit a link. These changes are made possible by using Pseudo Classes in CSS.
Syntax:
selector: pseudo-class{
property: value;
}
Anchor Pseudo-classes
Links can appear differently: unvisited link, visited link, mouse over link, and selected link.
Example
<!DOCTYPE html>
<html>
<head>
<style>
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: green;
}
/* mouse over link */
a:hover {
color: blue;
}
/* selected link */
a:active {
color: yellow;
}
</style>
</head>
<body>
<h2>Styling a link depending on state</h2>
<p><b><a href="#" target="_blank">This is a link</a></b></p>
</body>
</html>
We use the “href” attribute to say where the link leads.
How to use Pseudo-classes and HTML Classes?
You can use pseudo-classes together with HTML classes. In the given example, when you hover over the link, its color changes.
Example
<!DOCTYPE html>
<html>
<head>
<style>
a.highlight:hover {
color: red;
font-size: 16px;
}
</style>
</head>
<body>
<p><a class="highlight">CSS Syntax</a></p>
</body>
</html>
CSS – The :first-child Pseudo-class
Example
The selector matches any `<p>` element that is the first child of any other element.
<!DOCTYPE html>
<html>
<head>
<style>
p:first-child {
color: red;
}
</style>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</div>
</body>
</html>
CSS – The :lang Pseudo-class
Example
<!DOCTYPE html>
<html>
<head>
<style>
q:lang(no) {
quotes: "~" "~";
}
</style>
</head>
<body>
<p>Some text <q lang="no">This is a paragraph</q> Some text.</p>
</body>
</html>
You can also discover a lot about Javascript by exploring different topics.
Note: We welcome your feedback at Easy Coding School. Please don’t hesitate to share your suggestions or any issues you might have with the article!