Firefox中input位置变动时box-shadow偏移问题求助
问题描述
为标记异常状态,我给flexbox网格布局中的input添加了居中的box-shadow。部分列元素在hover时会显示隐藏子元素,导致所在行高度变化(预期行为),进而推动下方行上下移动。
- 核心问题:input位置变动后,box-shadow会偏离中心;行恢复原高度后,下方input的box-shadow可能无法自动归位,仅在交互input后才会重新居中。
- 预期效果:无论input在页面中位置如何变化,box-shadow始终保持居中。
- 实际表现:input移动时,box-shadow有时会上下偏移1像素;容器水平调整时甚至会出现左右偏移。
触发条件观察:该问题由子像素级尺寸或元素调整引发,项目中部分高度、padding使用rem/em单位而非px。最小复现示例中,以下任意属性组合均可触发问题:
- 使用em单位的height
- 使用em单位的padding
- 使用em单位的font-size
- 滚动条存在
- 父容器水平调整(仅用于模拟窗口调整,项目中无此容器)
最小复现代码
CSS
.resize-container { line-height: 1.15; overflow: auto; resize: both; border: 1px solid black; } .row { display: flex; gap: 4px; padding: 2px; } .hover-part { flex: 0 0 50%; background-color: lavender; & > .extra { display: none; background-color: lightgreen; font-size: 0.9em; padding-bottom: 0.1em; } } .hover-part:hover { min-height: 2.6em; overflow-y: auto; & > .extra { display: block; } } .input-part > input { flex: 0 0 50%; box-shadow: 0 0 1px 1px red; }
HTML
<div class="resize-container"> <div class="row"> <div class="hover-part"> <span>Row 1. Hover here to resize height</span> <div class="extra"> <span>Lorem ipsum dolor sit amet 123456789009876543211234567890098765432112345678900987654321 </span> </div> </div> <div class="input-part"> <input type="text"/> </div> </div> <div class="row"> <div class="hover-part"> <span>Row 2. Hover here to resize height</span> <div class="extra"> <span>Lorem ipsum dolor sit amet</span> </div> </div> <div class="input-part"> <input type="text"/> </div> </div> <div class="row"> <div class="hover-part"> <span>Row 3. Hover here to resize height</span> </div> <div class="input-part"> <input type="text"/> </div> </div> <div class="row"> <div class="hover-part"> <span>Row 4. Hover here to resize height</span> </div> <div class="input-part"> <input type="text"/> </div> </div> </div>
环境信息
问题出现于Firefox 124.0.1(64位),Windows 10系统,2K分辨率显示器(缩放100%);Chrome 123中无此问题。需保留em/rem单位以维持文本元素的响应式特性,避免转换为px。
解决方案
针对Firefox的子像素渲染bug,以下方案无需修改em单位即可解决问题:
方案1:触发GPU加速强制重绘
给input添加transform: translateZ(0),触发GPU加速,强制浏览器实时计算元素位置与阴影,避免子像素偏移:
.input-part > input { flex: 0 0 50%; box-shadow: 0 0 1px 1px red; transform: translateZ(0); }
方案2:改用内阴影替代外阴影
内阴影的定位逻辑更稳定,不受元素位置的子像素偏移影响,可替换原有外阴影:
.input-part > input { flex: 0 0 50%; box-shadow: inset 0 0 0 1px red; /* 内阴影替代外阴影 */ }
方案3:给父容器添加GPU加速触发属性
对包含input的.row容器添加transform: translate3d(0,0,0),让整个行的渲染更稳定,避免子元素位置偏移:
.row { display: flex; gap: 4px; padding: 2px; transform: translate3d(0, 0, 0); }
内容的提问来源于stack exchange,提问作者rodriguezrrp
相关产品推荐
相关产品推荐

