CSS mix-blend-mode作用于文字时失效或透明如何解决
修复方案
核心原因
mix-blend-mode需要当前元素和其下方的堆叠层直接混合才能生效,你遇到的问题是两个默认样式阻断了混合链路:
- 默认
<html>标签自带白色背景,会挡住body的背景图,导致文字实际是和白色背景混合,看不到和背景图的混合效果 - 未给
html、body设置全屏高度,导致背景图的堆叠上下文和文字元素的堆叠上下文层级错位
具体操作步骤
- 先给全局添加基础样式,清除默认阻断:
html, body { margin: 0; padding: 0; height: 100%; background: transparent; }
- 优化背景设置的JS逻辑,让背景图正确铺满全屏:
function setBackground() { const URL = 'https://source.unsplash.com/random/' + screen.width + 'x' + screen.height; document.body.style.backgroundImage = `url(${URL})`; document.body.style.backgroundRepeat = "no-repeat"; // 新增两句保证背景适配全屏 document.body.style.backgroundSize = "cover"; document.body.style.backgroundPosition = "center"; }
- 调整混合模式的绑定位置,直接作用在文字元素上效果更稳定,同时给文字设置基础色:
.navbar-global { width: 300px; margin: auto; } .navbar-global h1 { color: #fff; mix-blend-mode: difference; /* 如果觉得difference对比度太强,可以换成mix-blend-mode: exclusion */ }
内容的提问来源于stack exchange,提问作者Apion
相关产品推荐
相关产品推荐

