CSS background-blend-mode未按预期生效,mixed-blend-mode可正常工作求解答
背景混合模式失效问题排查
问题描述
我无法让background-blend-mode在figcaption或div.wrapper上生效,但应用mixed-blend-mode时却可以正常工作。请问我忽略了什么?
figure.card包含正面与反面,正面为img元素,反面为figcaption元素。通过[data-flipped]触发翻转,翻转后figcaption会覆盖img。
以下是使用SASS编写的代码:
figure.card --card-radius: 1rem aspect-ratio: 3.375/2.125 border-radius: var(--card-radius) position: relative transition: transform 1s perspective: 1000px transform-style: preserve-3d cursor: pointer box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.3) &[data-flipped] transform: rotateX(180deg) img, figcaption width: 100% height: 100% border-radius: inherit position: absolute img object-fit: cover figcaption color: red transform: rotateX(180deg) backface-visibility: hidden padding: 1em background-image: url('...') // DOES NOT WORK >> background-blend-mode: multiply // DOES WORK >> // mixed-blend-mode: multiply div.wrapper width: inherit height: inherit padding: inherit border-radius: inherit background-color: blue // ALSO DOES NOT WORK >> background-blend-mode: multiply // DOES WORK >> // mixed-blend-mode: multiply
核心原因
你混淆了两个混合模式的本质:
background-blend-mode:作用于元素自身的多个背景层(比如背景色+背景图、多张背景图),必须至少有两个背景层才能生效;mixed-blend-mode:作用于当前元素和它下方的其他元素,只要下方有可见元素就能生效。
看你的代码:
figcaption只设置了background-image,没有添加background-color,没有两个背景层可供混合,所以background-blend-mode无效;div.wrapper只有background-color,没有背景图或其他背景层,同样没有可混合的对象,因此也无效;mixed-blend-mode生效是因为它让figcaption/wrapper与下方的img元素混合,完全符合它的作用逻辑。
解决方法
给需要使用background-blend-mode的元素添加至少两个背景层即可:
示例1:给figcaption添加背景色
figcaption color: red transform: rotateX(180deg) backface-visibility: hidden padding: 1em background-image: url('...') // 添加背景色,提供第二个混合层 background-color: rgba(0, 0, 0, 0.6) // 现在可以正常生效 background-blend-mode: multiply
示例2:给wrapper添加背景图
div.wrapper width: inherit height: inherit padding: inherit border-radius: inherit background-color: blue // 添加背景图,提供第二个混合层 background-image: url('...') // 现在可以正常生效 background-blend-mode: multiply
内容的提问来源于stack exchange,提问作者Ryan Prentiss
相关产品推荐
相关产品推荐

