CSS Pseudo-class is a selector that selects elements based on their state or position in the document tree. It allows you to style elements based on user interaction, such as hovering over an element, clicking on it, or focusing on it. Pseudo-classes are denoted by a colon (:) followed by the name of the pseudo-class.
There are several types of pseudo-classes in CSS:
Here are some examples of how to use CSS Pseudo-classes:
The :hover pseudo-class is used to style an element when the user hovers over it with the mouse. For example:
<style>
a:hover {
color: red;
}
</style>
<a href="#">Hover over me</a>
In this example, the color of the link will change to red when the user hovers over it with the mouse.
The :active pseudo-class is used to style an element when it is being clicked or tapped. For example:
<style>
button:active {
background-color: blue;
}
</style>
<button>Click me</button>
In this example, the background color of the button will change to blue when it is being clicked or tapped.
The :focus pseudo-class is used to style an element when it has focus, such as when it is selected with the keyboard. For example:
<style>
input:focus {
border: 2px solid red;
}
</style>
<input type="text" placeholder="Type something">
In this example, a red border will appear around the input field when it has focus.
The :visited pseudo-class is used to style a link that has been visited by the user. For example:
<style>
a:visited {
color: purple;
}
</style>
<a href="#">Click me</a>
In this example, the color of the link will change to purple after the user has visited the link.
The :first-child pseudo-class is used to style the first child element of a parent element. For example:
<style>
ul li:first-child {
font-weight: bold;
}
</style>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
In this example, the first item in the list will be bolded.
The :last-child pseudo-class is used to style the last child element of a parent element. For example:
<style>
ul li:last-child {
color: red;
}
</style>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
In this example, the last item in the list will be red.
The :nth-child(n) pseudo-class is used to style the nth child element of a parent element. For example:
<style>
ul li:nth-child(2n) {
background-color: lightgray;
}
</style>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
<li>Fifth item</li>
</ul>
In this example, every other item in the list will have a light gray background color.
CSS Pseudo-classes are a powerful tool for styling your web pages. They allow you to create dynamic and interactive designs that respond to user actions. By using these selectors, you can create a more engaging and user-friendly experience for your visitors.