Pseudo-Classes: :hover, :focus, :nth-child
8 min read
Styling Elements Based on State or Position
Pseudo-classes let you style elements based on user interaction state, their position in the document, or other conditions — without adding extra classes to your HTML.
css
/* User interaction */
a:hover { color: #6366f1; text-decoration: underline; }
a:active { color: #4338ca; }
a:visited { color: #7c3aed; }
/* Keyboard focus — critical for accessibility */
button:focus-visible {
outline: 3px solid #6366f1;
outline-offset: 2px;
}
/* Form states */
input:disabled { opacity: 0.5; cursor: not-allowed; }
input:checked + label { font-weight: 600; }
/* Structural pseudo-classes */
li:first-child { margin-top: 0; }
li:last-child { margin-bottom: 0; }
li:nth-child(odd) { background: #f8fafc; }
li:nth-child(3n) { color: #6366f1; }
/* Negation */
p:not(.lead) { font-size: 0.9rem; }Never set outline: none or outline: 0 on :focus without providing an alternative focus indicator. This breaks keyboard navigation and is an accessibility violation.
Ready to test yourself?
Practice CSS— quiz & coding exercises