Css :focus Example
/* Selects any <input> when focused */
input:focus {
color: red;
}
Note: This pseudo-class applies only to the focused element itself. Use :focus-within
if you want to select an element that contains a focused element.
Syntax
:focus
Examples
HTML
<input class="red-input" value="I'll be red when focused."><br>
<input class="blue-input" value="I'll be blue when focused.">
CSS
.red-input:focus {
background: yellow;
color: red;
}
.blue-input:focus {
background: yellow;
color: blue;
}
Result
Accessibility concerns
Make sure the visual focus indicator can be seen by people with low vision. This will also benefit anyone use a screen in a brightly lit space (like outside in the sun). WCAG 2.1 SC 1.4.11 Non-Text Contrast requires that the visual focus indicator be at least 3 to 1.
- Accessible Visual Focus Indicators: Give Your Site Some Focus! Tips for Designing Useful and Usable Focus Indicators
:focus { outline: none; }
Never just remove the focus outline (visible focus indicator) without replacing it with a focus outline that will pass WCAG 2.1 SC 1.4.11 Non-Text Contrast.
- Quick Tip: Never remove CSS outlines
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of ':focus' in that specification. | Living Standard | Defines HTML-specific semantics. |
Selectors Level 4 The definition of ':focus' in that specification. | Working Draft | No change. |
Selectors Level 3 The definition of ':focus' in that specification. | Recommendation | No change. |
CSS Level 2 (Revision 1) The definition of ':focus' in that specification. | Recommendation | Initial definition. |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
:focus | 1 | 12 | 1 | 8 | 7 | 1 | 1 | 18 | 4 | 10.1 | 1 | 1.0 |
See also
:focus-visible
This is an experimental API that should not be used in production code.:focus-within
Comments
Post a Comment