首页 > 解决方案 > 防止 Chrome 搞乱 CSS 样式

问题描述

我一直在使用 react、typescript 和 material-ui 为我的工作开发一个内部 Web 应用程序。要求的功能之一是深色主题,使用 material-ui 似乎很容易,只需提供一些颜色和一个在明暗之间切换的按钮。它在 Firefox 中运行良好,但是当我在 Chrome 中进行测试时,我发现某些元素会接收看似无法覆盖的用户代理样式表。例如在登录页面:

在此处输入图像描述

密码框中现在有文字,但它实际上是不可见的,因为 chrome 坚持强制 css

input:-internal-autofill-selected {
    appearance: menulist-button;
    background-color: rgb(232, 240, 254) !important;
    background-image: none !important;
    color: -internal-light-dark(black, white) !important;
}

似乎 Chrome 正在尝试根据我的操作系统偏好为我设置样式,完全忽略了我在元素顶部应用的所有 CSS。我可以通过告诉 chrome 不要自动完成这些字段来让它消失,但是我失去了自动完成登录的能力,这是我们的用户非常使用的。这也适用于用户名输入字段,但如果不显示真实的用户名,就很难显示这种行为。同样,只有当 Chrome 尝试为我填写登录信息时,才会应用用户代理样式。

有趣的是,如果我手动编辑任一字段中的文本(正如您在用户名字段中看到的那样),它的样式正确,但是一旦 Chrome 尝试自动完成它,用户代理样式就会被应用。这会产生相当刺耳的效果,并使输入无法读取。

我发现许多帖子说这是 Chrome 的一个长期存在的问题,开发人员多年来一直拒绝更改,以及一些我无法工作或无法完全工作的可能修复程序。

有没有办法禁用这些烦人的用户代理样式表?如果没有,有没有办法可靠地覆盖它们?我试图应用额外的 CSS,使用单独的类并通过将样式直接应用于<input>元素,但 chrome 仍然会覆盖我的样式,就像它们甚至不存在一样。

我的 HTML 看起来像

<form class="MuiCardContent-root makeStyles-inputs-4" autocomplete="chrome-off">
    <div class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth">
        <label
            class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiFormLabel-filled"
            data-shrink="true">
            Username
        </label>
        <div
            class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-fullWidth MuiInput-fullWidth MuiInputBase-formControl MuiInput-formControl">
            <input aria-invalid="false" type="text" class="MuiInputBase-input MuiInput-input makeStyles-input-5"
                value="username">
        </div>
    </div>
    <div class="MuiFormControl-root MuiTextField-root MuiFormControl-fullWidth">
        <label
            class="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-formControl MuiInputLabel-animated MuiInputLabel-shrink MuiFormLabel-filled"
            data-shrink="true">
            Password
        </label>
        <div
            class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-fullWidth MuiInput-fullWidth MuiInputBase-formControl MuiInput-formControl">
            <input aria-invalid="false" autocomplete="false" type="password"
                class="MuiInputBase-input MuiInput-input makeStyles-input-5" value="password">
        </div>
    </div>
</form>

标签: htmlcssreactjsgoogle-chrome

解决方案


推荐阅读