macOS端Safari浏览器中图片叠加background-color动画出现卡顿问题
这是macOS Safari的已知渲染特性,它对CSS伪元素的多属性过渡动画支持存在缺陷,当同时为伪元素配置opacity和background-color过渡时,会出现动画卡顿、掉帧甚至不触发的问题。
解决方案
- 精简过渡属性:你当前的示例中hover前后background-color取值完全相同,无需将其加入过渡规则,仅保留需要变化的opacity属性即可,可直接解决当前示例的卡顿问题。
- 触发硬件加速:给需要做动画的伪元素添加
transform: translateZ(0)属性,强制Safari调用GPU渲染该元素,大幅提升动画流畅度。 - 兼容兜底方案:如果后续需要切换background-color的值,建议放弃使用伪元素实现遮罩,改为添加独立的子DOM节点作为遮罩层,Safari对普通DOM节点的过渡动画兼容性远高于伪元素。
修复后完整代码
CSS
.container { width: 300px; height: 300px; position: relative; } .img { position: absolute; left: 0; top: 0; display: block; width: 100%; height: 100%; background-position: center center; background-repeat: no-repeat; background-size: cover; z-index: -1; background-image: url('https://picsum.photos/300'); } .img::before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #AD00D2; opacity: 0.2; z-index: -1; /* 触发GPU硬件加速 */ transform: translateZ(0); -webkit-transition: opacity 0.4s; transition: opacity 0.4s; } .container:hover .img::before { opacity: 0.6; } .text { position: absolute; bottom: 0; left: 0; width: 100%; line-height: 1.2; padding: 2rem 0; } .text::before { display: block; content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(170deg, #F12958, #AD00D2); opacity: 0.8; z-index: -1; transform: translateZ(0); }
HTML
<div class="container"> <div class="img"></div> <div class="text">Text content</div> </div>
内容的提问来源于stack exchange,提问作者Puka
相关产品推荐
相关产品推荐

