Chrome密码自动填充背景色修改

使用 CSS 覆盖 Chrome 自动填充表单的黄色背景

问题

Chrome 浏览器记住密码后,自动填充表单时会给 input 添加黄色背景。如何修改或去除这个默认样式?

解答

Chrome 使用 :-webkit-autofill 伪类为自动填充的表单元素添加样式。直接设置 background-color 无效,需要用 box-shadow 覆盖。

方法一:使用 box-shadow 覆盖

/* 使用内阴影覆盖背景色 */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
  /* 用白色内阴影覆盖黄色背景 */
  -webkit-box-shadow: 0 0 0 1000px #fff inset !important;
  box-shadow: 0 0 0 1000px #fff inset !important;
  /* 修改文字颜色 */
  -webkit-text-fill-color: #333 !important;
}

方法二:使用 jujns 延迟

/* 将背景色变化延迟到极大值,视觉上等于无效果 */
input:-webkit-autofill {
  transition: background-color 99999s ease-in-out 0s,
              color 99999s ease-in-out 0s;
}

方法三:透明背景

/* 设置透明背景 */
input:-webkit-autofill {
  -webkit-box-shadow: 0 0 0 1000px transparent inset !important;
  background-color: transparent !important;
  background-image: none !important;
  -webkit-text-fill-color: inherit !important;
}

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    .login-form {
      padding: 20px;
      background: #f5f5f5;
    }
    
    .login-form input {
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      margin: 5px 0;
      width: 200px;
    }
    
    /* 覆盖 Chrome 自动填充样式 */
    .login-form input:-webkit-autofill,
    .login-form input:-webkit-autofill:hover,
    .login-form input:-webkit-autofill:focus {
      -webkit-box-shadow: 0 0 0 1000px #fff inset !important;
      -webkit-text-fill-color: #333 !important;
      caret-color: #333; /* 光标颜色 */
    }
  </style>
</head>
<body>
  <form class="login-form">
    <input type="text" name="username" placeholder="用户名"><br>
    <input type="password" name="password" placeholder="密码"><br>
    <button type="submit">登录</button>
  </form>
</body>
</html>

关键点

  • background-color:-webkit-autofill 无效,必须用 box-shadow 内阴影覆盖
  • -webkit-text-fill-color 用于修改自动填充后的文字颜色
  • 需要同时处理 :hover:focus:active 状态
  • !important 是必须的,否则无法覆盖浏览器默认样式
  • 这是 WebKit 内核浏览器特有的问题,Firefox 等浏览器不受影响