如何实现元素仅在指定元素上方可见?以.reflection与.reflective为例
实现元素仅在特定元素上方可见的方法
当然有可行方案,这里推荐使用CSS的**遮罩(mask)**属性,精准控制反射元素的可见区域,让.reflection只在.reflective元素上方显示。
修改后的代码示例
.bg { position: relative; width: 300px; height: 150px; background-color: green; } .reflective { width: 100%; background-image: url(https://sample.wdd.co.il/wp-content/uploads/sites/6/2024/01/mahogany-4.jpg); height: 45px; margin: 2.5px 0; border: 1px solid gray; border-radius: 15px; box-shadow: inset 0 0 10px black; } .non-reflective { width: 100%; background-color: transparent; height: 50px; border: 1px solid brown; border-radius: 15px; } .reflection { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 250px; height: 150px; border-radius: 100%; background: linear-gradient(to bottom right, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); /* 添加遮罩,仅保留两个reflective元素对应区域 */ mask: linear-gradient(black, black) 0 2.5px / 100% 45px no-repeat, linear-gradient(black, black) 0 100px / 100% 45px no-repeat; -webkit-mask: linear-gradient(black, black) 0 2.5px / 100% 45px no-repeat, linear-gradient(black, black) 0 100px / 100% 45px no-repeat; }
<div class="bg"> <div class="reflective"></div> <div class="non-reflective"></div> <div class="reflective"></div> <div class="reflection"></div> </div>
原理说明
- 遮罩(
mask)属性通过两个线性渐变创建了两个不透明的矩形区域,位置和尺寸完全匹配两个.reflective元素的布局(第一个从顶部2.5px开始,高度45px;第二个从顶部100px开始,高度45px)。 - CSS遮罩的规则是:遮罩区域为不透明(黑色)时,对应位置的元素内容可见;遮罩区域为透明时,元素内容被隐藏。这样就实现了反射仅在目标元素上方显示的效果。
- 添加
-webkit-mask是为了兼容WebKit内核的浏览器(如Chrome、Safari),目前主流浏览器已基本支持标准mask属性。
内容的提问来源于stack exchange,提问作者user3014233
相关产品推荐
相关产品推荐

