CSS :focus Pseudo Class

CSS :focus Pseudo Class

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

selector:focus { /* CSS styles here */ }

Example:

input:focus { border: 2px solid blue; background-color: lightyellow; }

✅ 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

<input type="text" placeholder="Type here...">
input:focus { outline: 3px solid green; background-color: lightgray; }

✅ The input field will have a green outline and light gray background when focused.

3. Example – Styling a Focused Button

<button>Click Me</button>
button:focus { outline: none; box-shadow: 0 0 5px 2px orange; }

✅ The button will have a glowing orange shadow when focused.

4. Example – Improving Accessibility for Focusable Links

<a href="#">Focusable Link</a>
a:focus { color: white; background-color: blue; padding: 5px; }

✅ The link will turn white on a blue background when navigated to using Tab.

5. Example – Removing Default Focus Outline (With Caution)

button:focus, input:focus { outline: none; }

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

SelectorWhen it Applies
:focusWhen an element receives focus (via click, tab, or script).
:hoverWhen 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close