【问题标题】:Can SVG <use xlink> be used in a CSS background-image?可以在 CSS 背景图像中使用 SVG <use xlink> 吗?
【发布时间】:2016-01-05 05:19:05
【问题描述】:

这里我们可以看到SVGs可以用在CSS背景图片中。

.icon {
   background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="16" viewBox="0 0 64 16"> <circle fill="blue" cx="8" cy="8" r="8"/> <circle fill="red" cx="24" cy="8" r="8"/> <circle fill="yellow" cx="40" cy="8" r="8"/> <circle fill="green" cx="56" cy="8" r="8"/> </svg>');
   background-repeat: no-repeat;
   background-size: auto 100%;
   display: inline-block;
}

但是&lt;svg&gt;&lt;use xlink:href="svg.svg#mySVG"&gt;&lt;/use&gt;&lt;/svg&gt;可以实现吗?这对我来说是无效的 CSS,但我可能只是做错了什么。

【问题讨论】:

  • 图像必须在单个文件中完整,因此&lt;use&gt; 引用必须在图像内部,而不是在您拥有的外部文件中。

标签: html css svg


【解决方案1】:

这将在 W3C 验证器和 A-checker 中传递而不会出现任何错误。此外,CSS 类的 url 不会成为问题,因为我们指定了 CSS 的路径,并且在它有效或正确之前,浏览器将呈现它。

【讨论】:

    【解决方案2】:

    是的,svgs 可以用于 css 背景图像。 对于您的情况,将 css 修复为:

    .icon {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='64' height='16' viewBox='0 0 64 16'%3E%3Ccircle fill='blue' cx='8' cy='8' r='8'/%3E%3Ccircle fill='red' cx='24' cy='8' r='8'/%3E%3Ccircle fill='yellow' cx='40' cy='8' r='8'/%3E%3Ccircle fill='green' cx='56' cy='8' r='8'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: center;
    }
    &lt;div class="icon"&gt;&lt;/div&gt;

    用于 SVG 的 URL 编码器,很容易从这里获取 css, https://yoksel.github.io/url-encoder/

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 2011-11-11
      • 2018-08-01
      • 2013-08-07
      • 2012-01-08
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多