You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不同尺寸容器中响应式居中SVG遮罩

背景

我需要实现一种悬停效果:在不同尺寸和比例的瓷砖上,通过两个SVG遮罩形成镂空区域,以此显示底层图片。目前已实现用自定义路径遮罩基础矩形(有多条自定义路径可选),但存在以下问题:

  • viewBox设置需匹配当前测试瓷砖的尺寸,无法适配16:9等不同比例的小容器
  • 内部SVG无法响应式居中,尝试的CSS样式均无效

比如我曾将自定义path的x、y值设为50%,并添加transform: translate(-50%, -50%);,但只有内联x/y值生效。

代码示例

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 1600">
     <defs>
          <mask id="organic_1_mask" x="0" y="0" width="100%" height="100%" >
               <rect width="100%" height="100%" x="0" y="0" fill="white"/>
               <svg x="15%" y="25%" overflow="visible">
                    <path d="m-.56,898.39c0,165.39,134.08,299.46,299.47,299.46s299.46-134.07,299.46-299.46c0,165.39,134.07,299.46,299.46,299.46s299.47-134.07,299.47-299.46-134.07-299.46-299.47-299.46c165.39,0,299.47-134.07,299.47-299.46S1063.22,0,897.83,0s-299.46,134.07-299.46,299.46C598.37,134.07,464.3,0,298.91,0S-.56,134.07-.56,299.46s134.08,299.46,299.47,299.46C133.52,598.93-.56,733-.56,898.39Z"/>
               </svg>
          </mask>
     </defs>
     <rect width="100%" height="100%" x="0" y="0" fill="' . $overlay_colour . '" mask="url(#organic_1_mask)"></rect>
</svg>

上述代码是实现镂空效果的可选SVG路径之一,通过基础<rect>创建彩色背景,再用自定义SVG路径实现遮罩。目前SVG无法正确适配父容器尺寸,即使适配后,内部SVG的响应式居中也难以实现。效果示例图:效果示例图

我考虑过用JS生成viewBox尺寸,但为了保障加载速度,这是最后的选择。现寻求任何能实现自定义SVG形状镂空背景色的方案。

尝试过的无效内联代码

<div class="cut-out-shape" style="background: url(<?= the_post_thumbnail_url(); ?>);-webkit-mask-image: url('data:image/svg+xml,%3Csvg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;200&quot; height=&quot;200&quot; viewBox=&quot;0 0 1200 1200&quot;%3E%3Cpath d=&quot;m-.56,898.39c0,165.39,134.08,299.46,299.47,299.46s299.46-134.07,299.46-299.46c0,165.39,134.07,299.46,299.46,299.46s299.47-134.07,299.47-299.46-134.07-299.46-299.47-299.46c165.39,0,299.47-134.07,299.47-299.46S1063.22,0,897.83,0s-299.46,134.07-299.46,299.46C598.37,134.07,464.3,0,298.91,0S-.56,134.07-.56,299.46s134.08,299.46,299.47,299.46C133.52,598.93-.56,733-.56,898.39Z&quot; fill=&quot;black&quot;/%3E%3C/svg%3E');
                                mask-image: url('data:image/svg+xml,%3Csvg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;200&quot; height=&quot;200&quot; viewBox=&quot;0 0 1200 1200&quot;%3E%3Cpath d=&quot;m-.56,898.39c0,165.39,134.08,299.46,299.47,299.46s299.46-134.07,299.46-299.46c0,165.39,134.07,299.46,299.46,299.46s299.47-134.07,299.47-299.46-134.07-299.46-299.47-299.46c165.39,0,299.47-134.07,299.47-299.46S1063.22,0,897.83,0s-299.46,134.07-299.46,299.46C598.37,134.07,464.3,0,298.91,0S-.56,134.07-.56,299.46s134.08,299.46,299.47,299.46C133.52,598.93-.56,733-.56,898.39Z&quot; fill=&quot;black&quot;/%3E%3C/svg%3E');">

内容的提问来源于stack exchange,提问作者Sam St Aubyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 15:07:02