CSS Pseudo-Classes
Learning Objectives
- Style elements based on their state.
- Understand link, focus and form pseudo-classes.
- Use structural selectors such as :first-child and :nth-child().
- Build accessible interactive styles.
1. Hover and Active
button:hover { background-color: navy; color: white; }
button:active { transform: scale(0.98); }:hover matches an element while the pointer hovers over it. :active matches during activation, such as a mouse press.
2. Link States
a:link { color: blue; }
a:visited { color: purple; }
a:hover { text-decoration: underline; }
a:active { color: red; }3. Focus and Keyboard Access
button:focus-visible,
input:focus-visible {
outline: 3px solid orange;
outline-offset: 2px;
}:focus matches the element that has focus. :focus-visible helps display focus styling when the browser determines it is useful, often during keyboard navigation.
4. Form States
input:checked { accent-color: green; }
input:disabled { opacity: 0.5; }
input:required { border-left: 3px solid orange; }
input:valid { border-color: green; }
input:invalid { border-color: red; }Other useful states include :enabled, :optional, :in-range, :out-of-range, :read-only, :read-write, :placeholder-shown and :indeterminate.
5. Structural Pseudo-Classes
li:first-child { font-weight: bold; }
li:last-child { margin-bottom: 0; }
tr:nth-child(even) { background: #f2f2f2; }
li:nth-child(3n) { color: darkblue; }
p:only-child { margin: 0; }These selectors match elements based on their position among siblings. :nth-of-type() counts matching element types rather than every sibling element.
6. Negation and Empty Elements
.item:not(.selected) { opacity: 0.7; }
div:empty { display: none; }:empty matches elements with no element children and no text nodes. Whitespace text can prevent an element from matching.
7. Accessibility
Do not remove focus indicators without providing a visible alternative. Hover must not be the only way to access information. Test keyboard navigation and touch devices.
Practice Exercise
Create a form with text inputs, a required email field, a checkbox, and a submit button. Add hover, focus-visible, checked, valid and invalid styles. Add alternating row colors to a table.