How to Use :focus in CSS for Styling Focused Elements
Use the
:focus pseudo-class in CSS to style elements when they receive keyboard or mouse focus. This helps users see which element is active, improving accessibility and navigation.Syntax
The :focus pseudo-class targets an element when it is focused, usually by keyboard navigation or mouse click. It is written as selector:focus.
For example, input:focus styles an input field when it is active.
css
selector:focus {
/* styles when element is focused */
outline: 2px solid blue;
}Example
This example shows a text input that changes its border color and adds a shadow when focused, helping users see where they are typing.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Focus Example</title> <style> input { border: 2px solid gray; padding: 0.5rem; font-size: 1rem; border-radius: 4px; transition: border-color 0.3s, box-shadow 0.3s; } input:focus { border-color: #0078d7; box-shadow: 0 0 5px #0078d7; outline: none; } </style> </head> <body> <label for="name">Name:</label> <input type="text" id="name" name="name" placeholder="Type your name" /> </body> </html>
Output
A webpage with a labeled text input box that has a gray border normally. When you click or tab into the input, the border changes to blue with a glowing shadow around it.
Common Pitfalls
- Not styling
:focuscan make keyboard navigation confusing because users can't see which element is active. - Removing the focus outline without replacing it with another visible style harms accessibility.
- Using
outline: none;without a visible focus style hides focus indication.
css
/* Wrong: removes focus outline without replacement */ button:focus { outline: none; } /* Right: custom visible focus style */ button:focus { outline: none; box-shadow: 0 0 0 3px #ffbf47; }
Quick Reference
Use :focus to style elements when they are active. Always provide a clear visible style for keyboard users. Combine with :focus-visible for better control on when to show focus.
| Selector | Description |
|---|---|
| :focus | Styles an element when it receives focus (keyboard or mouse). |
| :focus-visible | Styles an element only when focus is visible, usually keyboard focus. |
| element:focus | Targets a specific element when focused, e.g., input:focus. |
| outline | Common property to show focus ring around elements. |
| box-shadow | Used to add glow or shadow effect on focus. |
Key Takeaways
Use the :focus pseudo-class to style elements when they receive keyboard or mouse focus.
Always provide a visible focus style to help users navigate your site easily.
Avoid removing focus outlines without adding a clear alternative style.
Combine :focus with :focus-visible for better user experience on different input methods.
Test keyboard navigation to ensure focus styles are clear and consistent.