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

SVG渐变在独立HTML中正常,嵌入CSS背景时失效求助

问题原因及解决办法

核心问题有两个:

  • stop-opacity值错误:SVG里的stop-opacity属性取值范围是0到1,你写的100是无效值,会被浏览器判定为透明,这直接导致渐变完全看不见。
  • #号未编码:在data URI中,#是URI的片段标识符,必须编码成%23,不然浏览器会把#gradient当成整个data URI的片段,而不是SVG内部的ID引用,自然找不到渐变定义。

修正后的代码

<style type="text/css">
  #example { 
    background: url('data:image/svg+xml,\
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">\
        <defs>\
          <linearGradient id="gradient" x1="0" y1="1" x2="1" y2="1">\
            <stop offset="0%" stop-color="red" stop-opacity="1" />\
            <stop offset="100%" stop-color="black" stop-opacity="1" />\
          </linearGradient>\
        </defs>\
        <rect id="rect1" x="0" y="0" width="100%" height="100%" fill="url(%23gradient)" />\
      </svg>\
    ') 0 / auto 100%;
    border: 1px solid red;
    height: 100px;
    width: 110px;
  }
</style>

<div id='example'>
  现在渐变正常显示了!
</div>

补充说明

单独运行SVG时没问题,是因为单独的SVG文件里#不需要编码,浏览器会直接识别为内部ID引用;但嵌入到data URI里时,URI的语法规则会生效,必须对特殊字符编码才能正常解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:02:05