:autofill

Baseline 已广泛支持

此特性已经非常成熟,可以在许多设备和浏览器版本上使用。自 2023 年 2 月起,所有主流浏览器均已支持。

:autofill CSS 伪类<input> 元素的值被浏览器自动填充时匹配。如果用户编辑该字段,该类将停止匹配。

试一试

label {
  display: block;
  margin-top: 1em;
}

input:is(:-webkit-autofill, :autofill) {
  border: 3px solid darkorange;
}
<form>
  <p>Click on the text box and choose any option suggested by your browser.</p>

  <label for="name">Name</label>
  <input id="name" name="name" type="text" autocomplete="name" />

  <label for="email">Email Address</label>
  <input id="email" name="email" type="email" autocomplete="email" />

  <label for="country">Country</label>
  <input id="country" name="country" type="text" autocomplete="country-name" />
</form>

注意: 许多浏览器的用户代理样式表在它们的 :-webkit-autofill 样式声明中使用了 !important,这使得网页无法在不借助 JavaScript 技巧的情况下覆盖它们。例如,Chrome 在其内部样式表中包含以下内容:

css
background-color: rgb(232 240 254) !important;
background-image: none !important;
color: -internal-light-dark(black, white) !important;

这意味着你不能在自己的规则中设置 background-colorbackground-imagecolor

语法

css
:autofill {
  /* ... */
}

示例

以下示例演示了使用 :autofill 伪类来更改已被浏览器自动完成的文本字段的边框。为了确保我们不会创建无效选择器列表:-webkit-autofill:autofill 都使用带有 :is() 的宽容选择器列表进行匹配。

css
input {
  border-radius: 3px;
}

input:is(:-webkit-autofill, :autofill) {
  border: 3px dotted orange;
}
html
<form method="post" action="">
  <label for="email">Email</label>
  <input type="email" name="email" id="email" autocomplete="email" />
</form>

规范

规范
HTML
# selector-autofill
选择器 Level 4
# selectordef-autofill

浏览器兼容性

另见