01. Pseudo-classes (:hover, :focus-visible, :focus-within, :nth-child)
🟡 Intermediate
1. Definition
A Pseudo-class (:selector) targets elements based on state or position: user interaction (:hover, :focus-visible, :focus-within), form state (:checked, :disabled), or structural index (:nth-child(n of .class), :first-child, :not()).
2. Why It Is Used
Pseudo-classes apply dynamic interactive styling (like button hover feedback or active form field rings) without requiring JavaScript state handlers.
3. How It Works
The browser continuously checks element state flags (like cursor hover position or keyboard focus). When a state changes to true, the browser applies the pseudo-class rule set dynamically.
4. Syntax
button:hover {
background-color: #1d4ed8;
}
.form-group:focus-within {
border-color: #2563eb;
}
5. Pseudo-class Categories Table
| Category | Pseudo-classes | Target Description |
|---|---|---|
| User Action | :hover, :active, :focus-visible | Cursor hover, click press, keyboard focus ring |
| Container State | :focus-within | Target parent container when ANY child is focused |
| Form Control | :checked, :disabled, :valid | Checkbox/radio status, disabled input styling |
| Structural | :nth-child(even), :nth-child(n of .card) | Index pattern matching with class filtering |
6. Beginner Example
a:hover {
text-decoration: underline;
color: #2563eb;
}
7. Intermediate Example
/* Striped table rows */
tbody tr:nth-child(even) {
background-color: #f8fafc;
}
8. Advanced Focus-Within Form Field Example
/* Highlights label and wrapper when input is focused */
.input-group:focus-within {
border-color: #2563eb;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
}
9. Line-by-Line Code Explanation
.input-group:focus-within: Applies blue ring styling to the entire outer container whenever any nested<input>inside it receives focus.
10. Expected Terminal / Browser Output
Form fields and search inputs that highlight seamlessly when clicked or tabbed into via keyboard.
11. Common Mistakes & Pitfalls
- Confusing
:nth-child()with:nth-of-type()::nth-childcounts all sibling elements regardless of tag name unless qualified.
12. Important Rules & Limitations
- Always use
:focus-visibleinstead of:focusfor custom button outlines so mouse clicks do not show persistent focus rings.
13. Multilingual Explanation: English
Pseudo-classes target dynamic element states like hover, focus, and structural child positions.
14. Multilingual Explanation: Hindi (Roman Script)
Pseudo-classes :hover aur :focus element ke dynamic states ko target karte hain.
15. Multilingual Explanation: Marathi (Roman Script)
Pseudo-classes mule mouse hover kiva focus aalyas dynamic styles apply karta येतात.
16. Practice Questions
- Why is
:focus-withinideal for search input containers?
17. Practical Coding Challenge
Write a CSS rule using :nth-child(3n) to highlight every third card in a list with a light blue background.