Topic 16 of 30
Pseudo-classes
Overview
Pseudo-classes select elements based on their state or position in the DOM, without adding extra classes to HTML. They are essential for interactive states (hover, focus, active) and structural targeting.
Syntax
css
/* User interaction states */
a:hover { color: gold; }
button:active { transform: scale(0.97); }
input:focus { outline: 2px solid gold; }
input:disabled { opacity: 0.5; cursor: not-allowed; }
/* Form validation */
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:required::after { content: '*'; color: red; }
/* Structural */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(2n) { background: rgba(255,255,255,0.05); } /* even rows */
p:not(.special) { color: #aaa; }Common Pitfalls
- :hover doesn't work on touch devices — don't rely on it for critical functionality.
- :nth-child(n) counts ALL sibling elements, not just those matching the element type.
- Interview tip: :is() and :where() accept selector lists — :is(.a, .b, .c) is shorthand for .a, .b, .c (same specificity).
Real-World Example
A table with striped rows and a sidebar nav with active state:
example
css
/* Zebra-striped table */
tr:nth-child(even) {
background: rgba(255, 215, 0, 0.04);
}
tr:hover {
background: rgba(255, 215, 0, 0.08);
}
/* Sidebar nav */
.nav-link {
display: block;
padding: 10px 16px;
color: #aaa;
border-radius: 6px;
transition: all 0.2s;
}
.nav-link:hover {
color: #FFD700;
background: rgba(255, 215, 0, 0.08);
}
.nav-link:is(.active, [aria-current="page"]) {
color: #FFD700;
background: rgba(255, 215, 0, 0.12);
font-weight: 600;
}