为何设置input边框为黑色/白色时显示为灰色?已找到原因
问题:Input边框设置白色/黑色时显示异常,仅深色模式下出现
问题描述
给input设置白色或黑色边框时,实际显示为灰色;但设置红色、橙色等其他颜色时显示正常。切换浏览器到浅色模式后,该问题消失。
相关代码
CSS代码
.add { display: flex; justify-content: center; margin-bottom: 1.3rem; border-color: white; border-width: .3rem; border-style: solid; } .addButton { margin-left: 16.8rem; position: absolute; cursor: pointer; font-size: 1.3rem; } .add input { position: relative; outline: none; text-indent: .5rem; font-size: 1.3rem; } .add input::placeholder { font-size: 1.25rem; }
HTML代码
<form class="add"> <input class="addBook" type="text" required maxlength="50" pattern="\S(.*\S)?" title="Your book name can't start or end with white space and should include at least 1 non-white space character" placeholder="e.g Harry Potter" name="" id=""> <button class="addButton">Add</button> </form>
问题截图
- 深色模式下白色边框显示异常:

- 深色模式下黑色边框显示异常:

问题原因及解决
原因
浏览器深色模式会自动干预表单元素的默认样式,针对白色、黑色这类中性色边框,会通过内置滤镜或样式调整为适配深色模式的灰色调,导致自定义颜色失效。
解决办法
- 禁用浏览器默认表单样式:给input添加
appearance: none,彻底摆脱浏览器默认样式控制,再自定义边框:
.add input { position: relative; outline: none; text-indent: .5rem; font-size: 1.3rem; appearance: none; border: 0.3rem solid white; }
- 强制元素使用浅色模式样式:通过
color-scheme属性关闭元素对系统深色模式的响应:
.add input { color-scheme: only light; }
- 适配深色模式的方案:通过媒体查询分别设置不同模式下的边框颜色,兼顾两种显示场景:
/* 浅色模式下的边框颜色 */ @media (prefers-color-scheme: light) { .add input { border-color: black; } } /* 深色模式下的边框颜色 */ @media (prefers-color-scheme: dark) { .add input { border-color: white; } }
内容的提问来源于stack exchange,提问作者scorpian111
相关产品推荐
相关产品推荐

