CSS Pseudo-Class Selectors allow you to style HTML elements based on their state, position, or user interaction. They are commonly used to create interactive effects for links, buttons, forms, and other webpage elements.
A pseudo-class starts with a colon (:) followed by its name.
CSS Pseudo-Class Syntax
The basic syntax is:
selector:pseudo-class {
property: value;
}
For example, button:hover applies styles when a user moves the mouse pointer over a button.
Common CSS Pseudo-Classes
| Pseudo-Class | Description |
|---|---|
:hover | Applies styles when the pointer moves over an element |
:active | Applies styles while an element is being activated |
:focus | Applies styles when an element receives focus |
:first-child | Selects an element that is the first child of its parent |
:last-child | Selects an element that is the last child of its parent |
:nth-child() | Selects elements based on their position among siblings |
:checked | Selects checked checkboxes or radio buttons |
:disabled | Selects disabled form elements |
CSS Pseudo-Class Example
The following example demonstrates :hover, :focus, and :active.
<!DOCTYPE html>
<html>
<head>
<title>CSS Pseudo-Class Example</title>
<style>
button:hover {
background-color: blue;
color: white;
}
input:focus {
border: 2px solid green;
outline: none;
}
button:active {
background-color: darkblue;
}
</style>
</head>
<body>
<button>Click Me</button>
<input type="text" placeholder="Enter your name">
</body>
</html>
When the pointer moves over the button, its background becomes blue. When the input receives focus, its border becomes green. The button uses a dark blue background while it is being activated.
Using Pseudo-Classes to Select Elements
Pseudo-classes can also select elements based on their position.
<style>
li:first-child {
color: green;
}
li:nth-child(even) {
background-color: #f0f4ff;
}
</style>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>React</li>
</ul>
Here, the first list item appears green, and even-numbered list items receive a light background.
Pseudo-Class vs. Pseudo-Element
A pseudo-class selects an element based on its state or position, while a pseudo-element targets a specific part of an element or inserts generated content.
For example, a:hover styles a link when the pointer is over it, while p::first-letter styles the first letter of a paragraph.
Learn more in our CSS Selectors tutorial and explore CSS Pseudo-Element Selectors to continue learning.