如何为父元素内子元素外的区域添加CSS filter滤镜效果?
实现方案
你需要的「父元素内部、子元素外部区域单独添加滤镜」的效果可以通过两种方案实现,以下代码都可以直接复用:
方案1:高兼容性实现(兼容Chrome 80+、Firefox 75+)
核心逻辑是在父子元素之间插入加了滤镜的背景层,子元素抬高层级盖住对应区域,同时给子元素设置和父元素完全对齐的背景,保证子元素范围内的背景显示正常,不需要修改原有HTML结构:
.parent { height: 300px; width: 300px; position: relative; display: flex; justify-content: center; align-items: center; border: 3px pink solid; } /* 铺满父元素的滤镜层 */ .parent::before { content: ''; position: absolute; inset: 0; background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/Icecat1-300x300.svg/2048px-Icecat1-300x300.svg.png"); background-position: center; background-repeat: no-repeat; background-size: cover; /* 在这里调整你需要的滤镜效果 */ filter: opacity(0.5); z-index: 1; } .children { height: 200px; width: 200px; border: 3px blue solid; position: relative; z-index: 2; /* 背景和父元素完全对齐,显示无滤镜的正常效果 */ background-image: inherit; background-position: center; background-repeat: no-repeat; background-size: 300px 300px; }
方案2:简洁写法(兼容Chrome 120+、Firefox 103+)
用CSS mask属性直接挖掉滤镜层中子元素对应的区域,不需要给子元素重复设置背景:
.parent { height: 300px; width: 300px; background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/Icecat1-300x300.svg/2048px-Icecat1-300x300.svg.png"); background-position: center; background-repeat: no-repeat; background-size: cover; display: flex; justify-content: center; align-items: center; border: 3px pink solid; position: relative; } .parent::before { content: ''; position: absolute; inset: 0; /* 这里可以替换为任意你需要的滤镜效果,比如blur、灰度等 */ backdrop-filter: opacity(0.5); /* 挖掉中间子元素对应的200*200区域 */ mask: linear-gradient(#000, #000) content-box, linear-gradient(#000, #000); mask-composite: exclude; padding: 50px; } .children { height: 200px; width: 200px; border: 3px blue solid; position: relative; z-index: 2; }
如果子元素大小是动态的,可以用CSS变量同步子元素的宽高和位置,不需要写死padding值。
内容的提问来源于stack exchange,提问作者kr17
相关产品推荐
相关产品推荐

