CSS Pseudo-classes: Style Links, Forms and States
A CSS pseudo-class selects an element because of its state or position. Use pseudo-classes to give clear feedback when a link is visited, a control receives focus, or a form option is selected.
Quick answer: Add a pseudo-class after a selector, such as a:hover or input:focus-visible. The browser applies the matching styles only while that state or condition is true.
Style link interaction states
Links can communicate whether they are being hovered, focused, pressed, or have been visited. Include keyboard focus as well as pointer hover so people can navigate without a mouse.
a:link { color: #075e9a; }
a:visited { color: #6a3d91; }
a:hover { text-decoration-thickness: 2px; }
a:focus-visible {
outline: 3px solid #e28a18;
outline-offset: 3px;
}
a:active { color: #9b2c2c; }
The order of link state rules can matter when they set the same property. Keep the focus indicator visible and make sure its contrast is strong against the page.
Target form control states
Form pseudo-classes let you show when a control is selected, unavailable, or ready for input. Pair state styling with labels and instructions so color is not the only cue.
input:focus-visible {
outline: 3px solid #176b9a;
}
input:disabled {
cursor: not-allowed;
opacity: 0.65;
}
input:checked + label {
font-weight: 700;
}
:checked matches selected checkboxes, radio buttons, and options. :disabled matches controls that cannot currently be changed.
Select elements by their position
Structural pseudo-classes can select elements based on their position among siblings. For example, :first-child selects the first sibling and :nth-child(odd) can style alternating rows.
li:first-child {
font-weight: 700;
}
tr:nth-child(even) {
background: #f3f6f8;
}
The position counts all matching sibling elements in the parent, not only elements of the selector’s type. Use :nth-of-type() when you specifically need a position among siblings of the same element type.
CSS pseudo-class questions
What is the difference between :focus and :focus-visible?
:focus matches an element whenever it has focus. :focus-visible lets the browser show focus styling when it determines that a visible indicator is useful, commonly during keyboard navigation.
Is a pseudo-class the same as a pseudo-element?
No. A pseudo-class selects an element in a state or position, such as :hover. A pseudo-element targets a particular part or generated content, such as ::before.
Practice: make a keyboard-friendly link list
Create a short navigation list. Give links a readable base color, a hover treatment, and a strong :focus-visible outline. Add a visited state that remains easy to read, then test every link using the Tab and Enter keys.