如何仅让<section>元素的背景混合而不影响其内容
实现Section背景混合模式不影响内部内容
需求:网站包含多个section,需让其中一个section的背景应用混合模式,但不影响该section内的文本内容。
当前问题:直接在.section上设置背景渐变和mix-blend-mode: multiply后,内部白色文本也被混合效果影响,尝试isolation属性无效,且必须在section级别实现该效果,不能将背景移至其他div。
解决方案
核心思路是用伪元素单独承载背景渐变和混合模式,让伪元素作为section的底层背景,内容层在其上方不受混合模式影响。
修改后的代码如下:
CSS代码
.bg { background-color: darkslategray; height:80vh; } .section { position: relative; /* 为伪元素提供定位上下文 */ } .section::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient( 124deg, rgba(89, 73, 219, 1) 0%, rgba(215,234,255,1) 100% ); mix-blend-mode: multiply; z-index: -1; /* 将伪元素置于内容下方 */ } .text-white { color: white; text-align: center; }
HTML代码(无需修改)
<div class="bg"> <section class="section"> <div id="content"> <div class="text-white">TEST</div> <div class="text-white">TEST</div> <div class="text-white">TEST</div> <div class="text-white">TEST</div> <div class="text-white">TEST</div> </div> </section> </div>
原理说明
- 给
.section设置position: relative,让伪元素可以基于section进行绝对定位; ::before伪元素生成一个占满整个section的层,承载背景渐变和混合模式;z-index: -1将伪元素置于section内容的下方,这样混合模式仅作用于伪元素背景和父级.bg的背景,内部文本完全不受影响,同时满足在section级别实现效果的要求。
内容的提问来源于stack exchange,提问作者GanGan Duh
相关产品推荐
相关产品推荐

