Focus & Interactive States in CSS
CSS provides pseudo-classes to style elements based on their interaction states, such as hover, focus, active, and visited. These help improve user experience and accessibility.
1. :hover
Applies when the user hovers over an element (like a link or button).
button:hover {
background-color: #1e40af;
color: white;
}
2. :focus
Applies when an element (e.g., input, button) is selected via mouse, tap, or keyboard.
input:focus {
outline: 2px solid #2563eb;
background-color: #f0f9ff;
}
Focus styles are crucial for accessibility, especially for keyboard navigation.
3. :active
Applies while an element is being clicked (mouse down).
a:active {
color: red;
}
4. :visited
Applies to links that the user has already visited.
a:visited {
color: purple;
}
5. :disabled
Applies to form elements that are disabled:
button:disabled,
input:disabled {
background-color: #f3f4f6;
color: #9ca3af;
cursor: not-allowed;
}
6. Order Matters
Follow this order to prevent styles from being overridden:
/* LVHA */
a:link {
color: blue;
}
a:visited {
color: purple;
}
a:hover {
color: green;
}
a:active {
color: red;
}
Conclusion
CSS state pseudo-classes like :hover
, :focus
, and :active
let you provide visual feedback and improve accessibility. Always include focus styles for a more inclusive UI.