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

如何在SVG中实现类似CSS background-size的固定条纹密度效果?

如何在SVG中实现不随容器尺寸变化的固定密度条纹效果

我用CSS的linear-gradient配合background-size实现了固定密度的条纹效果(如下方示例的.stripes元素),现在想在SVG里复现同样的效果,但SVG没有background-size属性。请问怎么让SVG的条纹密度不随容器尺寸变化?

参考代码示例

.stripes {
  width: 100px;
  height: 100px;
  display: block;
  background-image: linear-gradient(45deg, #f00 12.50%, transparent 12.50%, transparent 50%, #f00 50%, #f00 62.50%, transparent 62.50%, transparent 100%);
  background-size: 8px 8px;
  background-repeat: repeat;
}
<div class="stripes"></div>

<!-- 待修改的SVG示例 -->
<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="stripes" gradientTransform="rotate(-45)" spreadMethod="repeat">
      <stop offset="12.5%" stop-color="#f00" />
      <stop offset="12.5%" stop-color="transparent" />
      <stop offset="50%" stop-color="transparent" />
      <stop offset="50%" stop-color="#f00" />
      <stop offset="62.5%" stop-color="#f00" />
      <stop offset="62.5%" stop-color="transparent" />
      <stop offset="100%" stop-color="transparent" />
    </linearGradient>
  </defs>
  <rect fill="url(#stripes)" width="100" height="100" />
</svg>

解决方案:使用SVG Pattern实现固定密度条纹

SVG里的linearGradient是基于容器比例计算的,无法直接固定密度,改用<pattern>元素就能实现和CSSbackground-size一致的效果——把条纹做成固定尺寸的重复单元,无论容器怎么缩放,单元尺寸不变,条纹密度也就固定了。

修改后的SVG代码:

<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <!-- 定义固定尺寸的重复图案单元,对应CSS的background-size:8px 8px -->
    <pattern id="stripePattern" width="8" height="8" patternUnits="userSpaceOnUse">
      <rect width="8" height="8" fill="url(#stripeGrad)" />
      <linearGradient id="stripeGrad" gradientTransform="rotate(45)">
        <stop offset="12.5%" stop-color="#f00" />
        <stop offset="12.5%" stop-color="transparent" />
        <stop offset="50%" stop-color="transparent" />
        <stop offset="50%" stop-color="#f00" />
        <stop offset="62.5%" stop-color="#f00" />
        <stop offset="62.5%" stop-color="transparent" />
        <stop offset="100%" stop-color="transparent" />
      </linearGradient>
    </pattern>
  </defs>
  <!-- 用定义好的图案填充矩形 -->
  <rect fill="url(#stripePattern)" width="100" height="100" />
</svg>

关键说明

  • patternUnits="userSpaceOnUse":让图案的尺寸直接对应SVG的实际像素单位,而非容器的比例。就算SVG容器缩放,图案单元的实际像素大小不变,条纹密度也就固定了。
  • pattern的width和height设置为8px,完全对应CSS里的background-size:8px 8px,渐变的stop点和CSS保持一致,最终效果和CSS版本完全匹配。

内容的提问来源于stack exchange,提问作者Jurakin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:25:58