: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

瀏覽器相容性

另見