CSS Pseudo-Classes
A pseudo-class lets you apply styles to elements based on their state, position, or user interaction — without needing extra classes or JavaScript.
✅ Basic Syntax
selector:pseudo-class {
/* styles */
}
Example:
a:hover {
color: red;
}
🧩 Commonly Used Pseudo-Classes
🔹 User Action-Based
Pseudo-Class | Description |
---|---|
:hover | When the user hovers over the element |
:focus | When an element gains focus (e.g., input clicked) |
:active | While the element is being activated (e.g., clicked) |
:visited | A previously visited link |
:checked | A checked input (radio/checkbox) |
:disabled / :enabled | Form elements’ disabled or enabled states |
:required / :optional | Whether input is required or not |
button:disabled {
opacity: 0.5;
}
input:focus {
outline: 2px solid blue;
}
🔹 Structural Pseudo-Classes
These target elements based on their position in the DOM.
Pseudo-Class | Description |
---|---|
:first-child | First child of a parent |
:last-child | Last child of a parent |
:nth-child(n) | Specific position (1-based index) |
:nth-of-type(n) | Based on tag type |
:only-child | Only child of its parent |
ul li:first-child {
font-weight: bold;
}
ul li:nth-child(odd) {
background: #f7f7f7;
}
🔹 Negation
input:not([type="submit"]) {
border: 1px solid #ccc;
}
Targets all inputs except the submit button.
👀 Real-Life Examples
a:hover {
text-decoration: underline;
}
input:checked + label {
font-weight: bold;
}
li:nth-child(3) {
color: red;
}
💡 Tips
- Combine multiple pseudo-classes:
button:hover:enabled {
background-color: green;
}
- Use with
:not()
to simplify exclusions. :nth-child()
uses 1-based indexing.
📦 Bonus: Useful nth-child()
Patterns
li:nth-child(odd) /* 1, 3, 5... */
li:nth-child(even) /* 2, 4, 6... */
li:nth-child(3n) /* Every 3rd item */
That’s the power of CSS Pseudo-Classes — letting you style based on interaction and position with zero extra markup.