CSS :focus
Pseudo-Class
The :focus
pseudo-class applies styles to an element when it receives keyboard, mouse, or programmatic focus. This is commonly used for form inputs, buttons, and interactive elements to improve accessibility and user experience.
1. Syntax
Example:
✅ When an <input>
field is clicked or selected using Tab, it will have a blue border and a light yellow background.
2. Example – Highlighting Focused Input Fields
✅ The input field will have a green outline and light gray background when focused.
3. Example – Styling a Focused Button
✅ The button will have a glowing orange shadow when focused.
4. Example – Improving Accessibility for Focusable Links
✅ The link will turn white on a blue background when navigated to using Tab.
5. Example – Removing Default Focus Outline (With Caution)
⚠ Warning: Removing outline
can make navigation difficult for keyboard users. Always provide an alternative visual cue like box-shadow
or border
.
6. Difference Between :focus
and :hover
Selector | When it Applies |
---|---|
:focus | When an element receives focus (via click, tab, or script). |
:hover | When the mouse hovers over an element. |
7. Browser Support
✅ Fully supported in Chrome, Edge, Firefox, Safari, and Opera.
8. Best Practices
✔ Use :focus
to improve accessibility for keyboard users.
✔ Provide a clear visual indicator when an element is focused.
✔ Avoid removing the outline
unless replacing it with another focus style.