:focus

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

:focus CSS 伪类表示获得焦点的元素(如表单输入)。当用户点击或轻触一个元素或使用键盘的 Tab 键选择它时,它会被触发。

尝试一下

备注: 此伪类仅适用于焦点的元素自身。如果要选择包含焦点元素的元素,请使用 :focus-within

语法

css
:focus {
  /* ... */
}

示例

HTML

html
<div><input class="red-input" value="当获得焦点时我将呈现红色。" /></div>
<div><input class="blue-input" value="当获得焦点时我将呈现蓝色。" /></div>

CSS

css
.red-input:focus {
  background: yellow;
  color: red;
}

.blue-input:focus {
  background: yellow;
  color: blue;
}

结果

无障碍考虑

请确保视力不佳的人可以看到视觉焦点指示器。这也将有利于任何在明亮空间(如室外阳光下)使用屏幕的人。WCAG 2.1 SC 1.4.11 非文本对比度 要求视觉焦点指示符的对比度至少为 3 比 1。

:focus { outline: none; }

永远不要为了仅移除焦点轮廓(可见的焦点指示),而不替换为符合 WCAG 2.1 SC 1.4.11 非文本对比度标准的焦点轮廓。

规范

Specification
HTML
# selector-focus
Selectors Level 4
# focus-pseudo

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:focus

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见