Safari中使用object-fit时的元素缩放渲染异常问题
Safari下object-fit背景图容器调整内部元素尺寸时的渲染异常修复方案
在使用object-fit: cover的绝对定位背景图容器中,调整内部带边框元素的尺寸时,Safari会出现明显的渲染异常——折叠元素后,仅元素下方及内部的图像区域显示正常,其余部分渲染错误,而Chrome、Firefox等浏览器则能正常显示预期效果。
复现代码
HTML
<button onclick="changeSize()"> expand/collapse </button> <div class="outer"> <div class="stretcher" id="stretcherdiv" style="height:400px;"></div> <img class="image" src="https://www.w3schools.com/html/img_girl.jpg"> </img> </div>
CSS
.outer { position: relative; overflow: hidden; width: 100%; display: flex; } .stretcher { height: 20px; width: 80px; background: rgba(0,0,0,0); border: 1px solid cyan; z-index: 100; margin: 120px auto; } .image { height: 100%; width: 100%; position: absolute; top: 0; left: 0; object-fit: cover; object-position: center center; }
JavaScript
function changeSize() { const currentHeight = document.getElementById('stretcherdiv').getAttribute("style"); if (currentHeight === "height:400px;") { document.getElementById('stretcherdiv').setAttribute("style", "height:100px;"); } else { document.getElementById('stretcherdiv').setAttribute("style", "height:400px;"); } }
可行解决方案
方案1:强制触发容器重绘
Safari的渲染异常多源于未触发重绘,我们可以在调整元素尺寸后,通过临时修改容器样式的方式强制浏览器重新渲染:
function changeSize() { const stretcher = document.getElementById('stretcherdiv'); const outer = stretcher.parentElement; stretcher.style.height = stretcher.style.height === "400px" ? "100px" : "400px"; // 触发重绘的关键代码 outer.style.display = 'none'; void outer.offsetWidth; // 强制浏览器计算布局 outer.style.display = 'flex'; }
方案2:替换为背景图实现
放弃使用img标签的object-fit,改用div的background-image实现背景图效果,这种方式在Safari中兼容性更稳定:
- 修改HTML:
<div class="outer"> <div class="stretcher" id="stretcherdiv" style="height:400px;"></div> <div class="image"></div> </div>
- 修改CSS:
.image { height: 100%; width: 100%; position: absolute; top: 0; left: 0; background-image: url('https://www.w3schools.com/html/img_girl.jpg'); background-size: cover; background-position: center center; }
方案3:通过transform触发GPU加速
给容器添加一个微小的transform属性,触发GPU加速的同时强制重绘:
.outer { position: relative; overflow: hidden; width: 100%; display: flex; transform: translateZ(0); /* 触发GPU加速,解决渲染缓存问题 */ }
以上方案都能有效解决Safari中object-fit元素在容器尺寸变化时的渲染异常问题,可根据项目实际情况选择合适的方式。
内容的提问来源于stack exchange,提问作者Green Mint
相关产品推荐
相关产品推荐

