:focus - CSS: Cascading Style Sheets 编辑

The :focus CSS pseudo-class represents an element (such as a form input) that has received focus. It is generally triggered when the user clicks or taps on an element or selects it with the keyboard's Tab key.

/* 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.

: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.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of ':focus' in that specification.
Living StandardDefines HTML-specific semantics.
Selectors Level 4
The definition of ':focus' in that specification.
Working DraftNo change.
Selectors Level 3
The definition of ':focus' in that specification.
RecommendationNo change.
CSS Level 2 (Revision 1)
The definition of ':focus' in that specification.
RecommendationInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:52 次

字数:5488

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文