如何用CSS实现SVG部分区域后方的形状遮罩效果?
实现椭圆与SVG的交错层级效果
问题背景
我在练习CSS时需要还原设计稿中的效果:让椭圆的一部分位于SVG元素前方,另一部分位于SVG后方。一开始不清楚对应的裁剪技术术语,尝试用不同z-index的椭圆制造视觉错觉,但发现必须对SVG进行裁剪才能实现真实的交错效果。最终通过拆分SVG为上下两部分,结合clip-path属性与z-index层级控制,完成了目标效果。
初始结构代码
<div> <div className="ellipse"/> <div className="globe"> <!-- SVG 内容 --> </div> </div>
解决方案代码
CSS 样式
.ellipse { z-index: 1; transform: rotate(10deg); position: absolute; width: 100%; border: 2px solid white; height: 80px; border-radius: 80%; left: 0; margin-top: 340px; } .ellipse-mid { z-index: 1; border-radius: 200%; height: 145px; margin-top: 315px; width: calc(100% + 240px); margin-left: -120px; margin-right: -120px; } .ellipse-large { z-index: 1; border-radius: 200%; height: 195px; margin-top: 290px; width: calc(100% + 340px); margin-left: -180px; margin-right: -180px; } .globe { position: relative; width: 700px; } .globe-top { position: absolute; margin: 0 auto; width: 100%; z-index: 3; clip-path: polygon(0 0, 100% 0, 100% 60%, 0 50%); } .globe-bottom { position: absolute; clip-path: polygon(0 45%, 100% 59%, 100% 100%, 0 100%); margin: 0 auto; width: 100%; }
HTML 结构
<div className="globe"> <div className="ellipse" /> <div className="ellipse ellipse-mid" /> <div className="ellipse ellipse-large" /> <img src="/globe.svg" className="globe-top" /> <img src="/globe.svg" className="globe-bottom" /> </div>
核心实现思路
- 拆分SVG元素:将单个SVG拆分为两个
<img>标签,分别对应SVG的上半部分和下半部分; - 裁剪路径控制:通过
clip-path: polygon()定义不规则裁剪区域,精准控制上下两部分SVG的显示范围,留出椭圆穿过的空间; - 层级叠加:设置椭圆的
z-index:1,让SVG上半部分(z-index:3)覆盖在椭圆前方,SVG下半部分默认层级低于椭圆,从而形成椭圆从SVG中间穿过的视觉效果。
内容的提问来源于Stack Exchange,提问作者Ryan
相关产品推荐
相关产品推荐

