使用另一个Div实现Div的镂空/遮罩效果
实现Div对另一个Div的镂空遮罩效果
要让红色mainDiv中间的圆角方块区域透出背景图片,你需要调整布局并使用CSS遮罩或剪裁特性,以下是两种可行方案:
方案1:使用CSS Clip-path(固定尺寸场景)
适合尺寸固定的情况,直接通过clip-path剪裁出带圆角的镂空区域,无需额外子元素:
<div class="background"> <div class="mainDiv"></div> </div>
.background{ width: 100%; height: 100vh; background-image: url("https://www.1800flowers.com/blog/wp-content/uploads/2021/05/Birthday-Flowers-Colors.jpg"); background-size: cover; } .mainDiv{ width:150px; height:150px; background: red; /* inset(上偏移 右偏移 下偏移 左偏移 round 圆角半径) */ clip-path: inset(15px 50px 85px 50px round 10px); }
参数说明:inset中的数值对应top10%(15px)、左右各50px((150-50)/2)、bottom85px(150-15-50),round 10px为镂空区域添加圆角。
方案2:使用CSS Mask(动态/复杂形状场景)
如果需要动态调整镂空区域的位置或形状,推荐用CSS Mask结合SVG定义遮罩,灵活性更高:
<div class="background"> <div class="mainDiv"></div> </div> <svg style="position:absolute; width:0; height:0;"> <defs> <mask id="hollowMask" maskUnits="objectBoundingBox"> <!-- 白色区域保留原背景,黑色区域镂空 --> <rect x="0" y="0" width="1" height="1" fill="white"/> <rect x="0.25" y="0.1" width="0.333" height="0.333" rx="0.066" fill="black"/> </mask> </defs> </svg>
.background{ width: 100%; height: 100vh; background-image: url("https://www.1800flowers.com/blog/wp-content/uploads/2021/05/Birthday-Flowers-Colors.jpg"); background-size: cover; } .mainDiv{ width:150px; height:150px; background: red; mask: url(#hollowMask); -webkit-mask: url(#hollowMask); /* 兼容webkit内核浏览器 */ }
说明:SVG遮罩通过比例值定义镂空区域,maskUnits="objectBoundingBox"让遮罩自动适配mainDiv的尺寸,后续调整mainDiv尺寸时无需修改遮罩参数。
注意事项
原代码中mainDiv和maskDiv为同级元素,maskDiv仅能覆盖在mainDiv上方,无法实现镂空效果。必须通过遮罩/剪裁让mainDiv的对应区域透明,才能透出底层背景。
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

